target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
test/StyleSheetRegistrySpec.js
michalkvasnicak/stylo
import { expect } from 'chai'; import StyleSheetRegistry from '../src/StyleSheetRegistry'; import StyleSheet from '../src/StyleSheet'; import { stub, spy } from 'sinon'; import jsdom from './jsdom'; import React from 'react'; describe('StyleSheetRegistry', () => { describe('#styleElement()', () => { let registry; let insertRule; beforeEach(() => { registry = new StyleSheetRegistry(); registry._insertRule = insertRule = spy(); }); it('skips element styling if element does not have styles prop and returns it', () => { const element = <div className="cls"></div>; const styledElement = registry.styleElement(element, {}); expect(element).to.be.equal(styledElement); }); describe('server side', () => { it('does not style element using non StyleSheet styles', () => { const element = <div></div>; let styledElement; styledElement = registry.styleElement(element, { className: 'cls', styles: false }); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls'); styledElement = registry.styleElement(element, { className: 'cls', styles: [false, null, true, 10, 'pom', {}]}); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls'); }); it('styles element using StyleSheet styles', () => { const styleSheet = stub(new StyleSheet({})); const styleSheet2 = stub(new StyleSheet({ ':hover': { fontSize: '10px' }})); // restore to use original implementation styleSheet.toMD5.restore(); styleSheet2.toMD5.restore(); styleSheet.rules.returns([{ toString: () => '.cls_1{}'}]); styleSheet2.rules.returns([{ toString: () => '.cls_2{}'}]); styleSheet.mediaQueries.returns([]); styleSheet2.mediaQueries.returns([]); styleSheet.keyFrames.returns([]); styleSheet2.keyFrames.returns([]); const element = <div></div>; let styledElement; // one style styledElement = registry.styleElement(element, { className: 'cls', styles: styleSheet }); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls_1 cls'); expect(insertRule.getCall(0).args[0]).to.be.eq('.cls_1{}'); expect(insertRule.callCount).to.be.eq(1); // multiple styles styledElement = registry.styleElement(element, { className: 'cls', styles: [styleSheet, null, styleSheet2, 10, 'pom', {}]}); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls_1 cls_2 cls'); // cls_1 is not called because it is already registered expect(insertRule.getCall(1).args[0]).to.be.eq('.cls_2{}'); // duplicated styles styledElement = registry.styleElement(element, { className: 'cls', styles: [styleSheet, styleSheet, styleSheet2, 10, 'pom', {}]}); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls_1 cls_2 cls'); expect(insertRule.callCount).to.be.eq(2); }); }); describe('client side', () => { beforeEach(() => { const { document } = jsdom('<!doctype html><html><head><style id="style-sheet-registry"></style></head><body></body></html>'); global.window = document.defaultView; global.document = document; insertRule = global.document.querySelector('style').sheet.insertRule = spy(global.document.querySelector('style').sheet.insertRule); registry = new StyleSheetRegistry(); }); afterEach(() => { delete global.window; delete global.document; }); it('styles element using StyleSheet styles', () => { const styleSheet = stub(new StyleSheet({})); const styleSheet2 = stub(new StyleSheet({ ':hover': { fontSize: '10px' }})); // restore to use original implementation styleSheet.toMD5.restore(); styleSheet2.toMD5.restore(); styleSheet.rules.returns([{ toString: () => '.cls_1{}'}]); styleSheet2.rules.returns([{ toString: () => '.cls_2{}'}]); styleSheet.mediaQueries.returns([]); styleSheet2.mediaQueries.returns([]); styleSheet.keyFrames.returns([]); styleSheet2.keyFrames.returns([]); const element = <div></div>; let styledElement; // one style styledElement = registry.styleElement(element, { className: 'cls', styles: styleSheet }); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls_1 cls'); expect(insertRule.getCall(0).args[0]).to.be.eq('.cls_1{}'); expect(insertRule.getCall(0).args[1]).to.be.eq(0); expect(insertRule.callCount).to.be.eq(1); // multiple styles styledElement = registry.styleElement(element, { className: 'cls', styles: [styleSheet, null, styleSheet2, 10, 'pom', {}]}); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls_1 cls_2 cls'); // cls_1 is not called because it is already registered expect(insertRule.getCall(1).args[0]).to.be.eq('.cls_2{}'); expect(insertRule.getCall(1).args[1]).to.be.eq(1); // duplicated styles styledElement = registry.styleElement(element, { className: 'cls', styles: [styleSheet, styleSheet, styleSheet2, 10, 'pom', {}]}); expect(styledElement).to.not.equal(element); expect(styledElement.props).to.not.have.property('styles'); expect(styledElement.props).to.have.property('className').that.is.equal('cls_1 cls_2 cls'); expect(insertRule.callCount).to.be.eq(2); }); }); }); describe('#dehydrate()', () => { it('dehydrates internal state to simple JS object', () => { const registry = new StyleSheetRegistry(); const styleSheet = stub(new StyleSheet({ 'default': { color: '#000', padding: '10px' }})); const styleSheet2 = stub(new StyleSheet({ ':hover': { fontSize: '10px' }})); // restore to use original implementation styleSheet.toMD5.restore(); styleSheet2.toMD5.restore(); styleSheet.rules.returns([{ toString: () => '.cls_1{color:#000;padding:10px}'}]); styleSheet2.rules.returns([{ toString: () => '.cls_2:hover{font-size:10px}'}]); styleSheet.mediaQueries.returns([{ toString: () => '@media all{.cls_1{color:#fff}}'}]); styleSheet2.mediaQueries.returns([]); styleSheet.keyFrames.returns([{ toString: () => '@keyframes resize{10%{color:#ff0000}}'}]); styleSheet2.keyFrames.returns([]); registry.styleElement(<div></div>, { className: 'cls', styles: [styleSheet, null, styleSheet2, 10, 'pom', {}]}); const state = registry.dehydrate(); expect(state).to.be.an('object'); expect(state).to.have.property('count').that.is.equal(2); expect(state).to.have.property('registered').that.is.an('object'); expect(Object.keys(state.registered)).to.have.property('length').that.is.equal(2); expect(state).to.have.property('rules').that.is.an('array').with.property('length').that.is.equal(4); }); }); describe('#rehydrate()', () => { it('rehydrates internal state from simple JS object', () => { const registry = new StyleSheetRegistry(); const styleSheet2 = stub(new StyleSheet({ ':hover': { fontSize: '10px' }})); styleSheet2.toMD5.restore(); styleSheet2.rules.returns([{ toString: () => '.cls_2:hover{font-size:10px}'}]); styleSheet2.mediaQueries.returns([]); styleSheet2.keyFrames.returns([]); registry.rehydrate({ count: 2, registered: { hash: 'cls_1', hash2: 'cls_2' }, rules: ['.cls_1{color:#000;padding:10px}', '.cls_2:hover{font-size:10px}'] }); expect(registry).to.have.property('count').that.is.equal(2); expect(registry).to.have.property('registered').that.is.an('object'); expect(registry).to.have.property('rules').that.is.an('array').with.property('length').that.is.equal(2); registry.styleElement(<div></div>, { className: 'cls', styles: styleSheet2}); expect(registry.count).to.be.equal(3); expect(registry.rules.length).to.be.equal(3); }); }); describe('#toString()', () => { it('returns CSS ruleset', () => { const registry = new StyleSheetRegistry(); const styleSheet = stub(new StyleSheet({ 'default': { color: '#000', padding: '10px' }})); const styleSheet2 = stub(new StyleSheet({ ':hover': { fontSize: '10px' }})); // restore to use original implementation styleSheet.toMD5.restore(); styleSheet2.toMD5.restore(); styleSheet.rules.returns([{ toString: () => '.cls_1{color:#000;padding:10px}'}]); styleSheet2.rules.returns([{ toString: () => '.cls_2:hover{font-size:10px}'}]); styleSheet.mediaQueries.returns([]); styleSheet2.mediaQueries.returns([]); styleSheet.keyFrames.returns([]); styleSheet2.keyFrames.returns([]); registry.styleElement(<div></div>, { className: 'cls', styles: [styleSheet, null, styleSheet2, 10, 'pom', {}]}); expect(registry.toString()).to.be.equal( '.cls_1{color:#000;padding:10px}.cls_2:hover{font-size:10px}' ); }); }); });
js/App/Components/Sensor/AddSensor/AddSensorContainer.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import { BackHandler, Keyboard, KeyboardAvoidingView, Platform } from 'react-native'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; const isEqual = require('react-fast-compare'); import { View, NavigationHeaderPoster, } from '../../../../BaseComponents'; import Theme from '../../../Theme'; import * as modalActions from '../../../Actions/Modal'; import { getGateways, sendSocketMessage, setDeviceName, getDevices, getDeviceManufacturerInfo, showToast, processWebsocketMessage, addDevice as addDeviceAction, setWidgetParamId, initiateAdd433MHz, deviceAdded, registerForWebSocketEvents, getDeviceInfoCommon, } from '../../../Actions'; type Props = { addDevice: Object, navigation: Object, children: Object, actions?: Object, screenProps: Object, currentScreen: string, ScreenName: string, locale: string, enableWebshop: boolean, processWebsocketMessage: (string, string, string, Object) => any, route: Object, }; type State = { h1: string, h2: string, infoButton: null | Object, keyboardShown: boolean, forceLeftIconVisibilty: boolean, }; export class AddSensorContainer extends View<Props, State> { handleBackPress: () => boolean; _keyboardDidShow: () => void; _keyboardDidHide: () => void; state: State = { h1: '', h2: '', infoButton: null, keyboardShown: false, forceLeftIconVisibilty: false, }; constructor(props: Props) { super(props); this.backButton = { back: true, onPress: this.goBack, }; this.handleBackPress = this.handleBackPress.bind(this); this._keyboardDidShow = this._keyboardDidShow.bind(this); this._keyboardDidHide = this._keyboardDidHide.bind(this); } componentDidMount() { BackHandler.addEventListener('hardwareBackPress', this.handleBackPress); this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow); this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); } shouldComponentUpdate(nextProps: Props, nextState: State): boolean { if (nextProps.ScreenName === nextProps.currentScreen) { const isStateEqual = isEqual(this.state, nextState); if (!isStateEqual) { return true; } const isPropsEqual = isEqual(this.props, nextProps); if (!isPropsEqual) { return true; } return false; } return false; } _keyboardDidShow() { this.setState({ keyboardShown: true, }); } _keyboardDidHide() { this.setState({ keyboardShown: false, }); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress); this.keyboardDidShowListener.remove(); this.keyboardDidHideListener.remove(); } handleBackPress(): boolean { const { navigation } = this.props; const { forceLeftIconVisibilty } = this.state; const allowBacknavigation = !this.disAllowBackNavigation() || forceLeftIconVisibilty; if (!allowBacknavigation) { return true; } navigation.pop(); return true; } disAllowBackNavigation(): boolean { const {currentScreen} = this.props; const screens = ['AlreadyIncluded', 'IncludeFailed', 'DeviceName', 'NoDeviceFound', 'ExcludeScreen', 'CantEnterInclusion']; return screens.indexOf(currentScreen) !== -1; } onChildDidMount: Function = (h1: string, h2: string, infoButton?: Object | null = null) => { this.setState({ h1, h2, infoButton, }); }; toggleLeftIconVisibilty: Function = (forceLeftIconVisibilty: boolean) => { this.setState({ forceLeftIconVisibilty, }); }; getLeftIcon: Function = (CS: string): ?string => { if (CS === 'SelectSensorType') { const { route, } = this.props; if (route.params && route.params.singleGateway) { return 'close'; } } const SCNS = ['SelectLocationAddSensor']; return SCNS.indexOf(CS) === -1 ? undefined : 'close'; }; render(): Object { const { children, actions, screenProps, currentScreen, navigation, addDevice, route, locale, sessionId, } = this.props; const { appLayout } = screenProps; const { h1, h2, infoButton, forceLeftIconVisibilty } = this.state; const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; const padding = deviceWidth * Theme.Core.paddingFactor; const showLeftIcon = !this.disAllowBackNavigation() || forceLeftIconVisibilty; const leftIcon = this.getLeftIcon(currentScreen); return ( <View level={3} style={{ flex: 1, }}> <NavigationHeaderPoster h1={h1} h2={h2} infoButton={infoButton} align={'left'} navigation={navigation} showLeftIcon={showLeftIcon} leftIcon={leftIcon} {...screenProps} currentScreen={currentScreen}/> <KeyboardAvoidingView behavior="padding" style={{flex: 1}} contentContainerStyle={{ flexGrow: 1, justifyContent: 'center', }} keyboardVerticalOffset={Platform.OS === 'android' ? -500 : 0}> {React.cloneElement( children, { onDidMount: this.onChildDidMount, actions, ...screenProps, currentScreen, navigation, paddingHorizontal: padding, addDevice, processWebsocketMessage: this.props.processWebsocketMessage, route, locale, toggleLeftIconVisibilty: this.toggleLeftIconVisibilty, sessionId, showLeftIcon, }, )} </KeyboardAvoidingView> </View> ); } } export const mapStateToProps = (store: Object): Object => { const { defaultSettings } = store.app; const { language = {} } = defaultSettings || {}; const locale = language.code; const { websockets: { session: { id: sessionId } }, user: { firebaseRemoteConfig = {} } } = store; const { webshop = JSON.stringify({enable: false}) } = firebaseRemoteConfig; const { enable: enableWebshop } = JSON.parse(webshop); const { screen: currentScreen, } = store.navigation; return { addDevice: store.addDevice, locale, sessionId, enableWebshop, currentScreen, }; }; export const mapDispatchToProps = (dispatch: Function): Object => ( { actions: { ...bindActionCreators({ ...modalActions, getGateways, sendSocketMessage, setDeviceName, getDevices, getDeviceManufacturerInfo, showToast, addDeviceAction, setWidgetParamId, initiateAdd433MHz, registerForWebSocketEvents, deviceAdded, getDeviceInfoCommon, }, dispatch), }, processWebsocketMessage: (gatewayId: string, message: string, title: string, websocket: Object): any => processWebsocketMessage(gatewayId, message, title, dispatch, websocket), } ); export default (connect(mapStateToProps, mapDispatchToProps)(AddSensorContainer): Object);
src/svg-icons/editor/vertical-align-top.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorVerticalAlignTop = (props) => ( <SvgIcon {...props}> <path d="M8 11h3v10h2V11h3l-4-4-4 4zM4 3v2h16V3H4z"/> </SvgIcon> ); EditorVerticalAlignTop = pure(EditorVerticalAlignTop); EditorVerticalAlignTop.displayName = 'EditorVerticalAlignTop'; EditorVerticalAlignTop.muiName = 'SvgIcon'; export default EditorVerticalAlignTop;
example/stories/simple.js
Kilix/storybook-addon-jsx
import React from 'react'; import { storiesOf } from '@storybook/react'; const Simple = ({ children }) => ( <div> <span>Hello</span> {children} </div> ); storiesOf('Simple Test', module) .addWithJSX('No children - No options', () => <Simple />) .addWithJSX('No children - Rename', () => <Simple />, { displayName: 'Renamed' }) .addWithJSX('With children - No options', () => ( <Simple> <span>World</span> </Simple> )) .addWithJSX( 'With children - Skip', () => ( <Simple> <span>World</span> </Simple> ), { skip: 1 } ) .addWithJSX( 'With children - Skip and rename', () => ( <Simple> <span>World</span> </Simple> ), { skip: 1, displayName: 'Renamed' } ) .addWithJSX('Data strings', () => ( <div data={`{"bar"}`} data-baz={`{"baz"}`} data-bat={`{"bat"}`} /> ));
react-ui/src/components/portifolio/Gallery.js
MaGuangChen/resume-maguangchen
import React from 'react'; const Gallery = (props) => { const { background, title, text, link } = props; const backgroundStyle = { background: `url(${background})center no-repeat`, backgroundSize: 'cover' } const linkTo = (e) => { e.preventDefault(); window.open(`${link}`,'_blank'); } return ( <div onClick={linkTo} style={backgroundStyle}> <p> <a href={link} target="_blank">{title}</a> <a>{text}</a> </p> </div> ) } export default Gallery;
packages/reactor-modern-boilerplate/src/About/About.js
markbrocato/extjs-reactor
import React from 'react'; import { Container } from '@extjs/reactor/modern'; export default function About() { return ( <Container padding="20"> <h1>About this App</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam eget leo sed mi imperdiet dictum a id turpis. Suspendisse a ante eu lorem lacinia vestibulum. Suspendisse volutpat malesuada ante, sed fermentum massa auctor in. Praesent semper sodales feugiat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris mauris ante, suscipit id metus non, venenatis tempor tortor. In ornare tempor ipsum. Sed rhoncus augue urna, ut dapibus odio fringilla vitae. Phasellus malesuada mauris ut nulla varius sodales. Sed et leo luctus, venenatis felis sit amet, vehicula nibh. Curabitur fringilla fringilla nibh, porttitor lacinia urna vestibulum eu. Integer ac aliquet risus. Curabitur imperdiet quis purus at consectetur. Sed ornare vitae felis a scelerisque. Donec mi purus, auctor sit amet molestie nec, imperdiet auctor mauris.</p> </Container> ) }
packages/material-ui-icons/src/VideocamOffTwoTone.js
callemall/material-ui
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M12.39 8L15 10.61V8zM5 8v8h9.73l-8-8z" opacity=".3" /><path d="M3.41 1.86L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.55-.18L19.73 21l1.41-1.41L3.41 1.86zM5 16V8h1.73l8 8H5zm10-8v2.61l6 6V6.5l-4 4V7c0-.55-.45-1-1-1h-5.61l2 2H15z" /></React.Fragment> , 'VideocamOffTwoTone');
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);
client/src/components/Explorer/ExplorerPanel.js
nimasmi/wagtail
import PropTypes from 'prop-types'; import React from 'react'; import FocusTrap from 'focus-trap-react'; import { STRINGS, MAX_EXPLORER_PAGES } from '../../config/wagtailConfig'; import Button from '../Button/Button'; import LoadingSpinner from '../LoadingSpinner/LoadingSpinner'; import Transition, { PUSH, POP } from '../Transition/Transition'; import ExplorerHeader from './ExplorerHeader'; import ExplorerItem from './ExplorerItem'; import PageCount from './PageCount'; /** * The main panel of the page explorer menu, with heading, * menu items, and special states. */ class ExplorerPanel extends React.Component { constructor(props) { super(props); this.state = { transition: PUSH, paused: false, }; this.onItemClick = this.onItemClick.bind(this); this.onHeaderClick = this.onHeaderClick.bind(this); this.clickOutside = this.clickOutside.bind(this); } componentWillReceiveProps(newProps) { const { path } = this.props; const isPush = newProps.path.length > path.length; this.setState({ transition: isPush ? PUSH : POP, }); } componentDidMount() { document.querySelector('[data-explorer-menu-item]').classList.add('submenu-active'); document.body.classList.add('explorer-open'); document.addEventListener('mousedown', this.clickOutside); document.addEventListener('touchend', this.clickOutside); } componentWillUnmount() { document.querySelector('[data-explorer-menu-item]').classList.remove('submenu-active'); document.body.classList.remove('explorer-open'); document.removeEventListener('mousedown', this.clickOutside); document.removeEventListener('touchend', this.clickOutside); } clickOutside(e) { const { onClose } = this.props; const explorer = document.querySelector('[data-explorer-menu]'); const toggle = document.querySelector('[data-explorer-menu-item]'); const isInside = explorer.contains(e.target) || toggle.contains(e.target); if (!isInside) { onClose(); } if (toggle.contains(e.target)) { this.setState({ paused: true, }); } } onItemClick(id, e) { const { pushPage } = this.props; e.preventDefault(); e.stopPropagation(); pushPage(id); } onHeaderClick(e) { const { path, popPage } = this.props; const hasBack = path.length > 1; if (hasBack) { e.preventDefault(); e.stopPropagation(); popPage(); } } renderChildren() { const { page, nodes } = this.props; let children; if (!page.isFetching && !page.children.items) { children = ( <div key="empty" className="c-explorer__placeholder"> {STRINGS.NO_RESULTS} </div> ); } else { children = ( <div key="children"> {page.children.items.map((id) => ( <ExplorerItem key={id} item={nodes[id]} onClick={this.onItemClick.bind(null, id)} /> ))} </div> ); } return ( <div className="c-explorer__drawer"> {children} {page.isFetching ? ( <div key="fetching" className="c-explorer__placeholder"> <LoadingSpinner /> </div> ) : null} {page.isError ? ( <div key="error" className="c-explorer__placeholder"> {STRINGS.SERVER_ERROR} </div> ) : null} </div> ); } render() { const { page, onClose, path } = this.props; const { transition, paused } = this.state; return ( <FocusTrap tag="div" role="dialog" className="explorer" paused={paused || !page || page.isFetching} focusTrapOptions={{ initialFocus: '.c-explorer__header', onDeactivate: onClose, }} > <Button className="c-explorer__close u-hidden" onClick={onClose}> {STRINGS.CLOSE_EXPLORER} </Button> <Transition name={transition} className="c-explorer" component="nav" label={STRINGS.PAGE_EXPLORER}> <div key={path.length} className="c-transition-group"> <ExplorerHeader depth={path.length} page={page} onClick={this.onHeaderClick} /> {this.renderChildren()} {page.isError || page.children.items && page.children.count > MAX_EXPLORER_PAGES ? ( <PageCount page={page} /> ) : null} </div> </Transition> </FocusTrap> ); } } ExplorerPanel.propTypes = { nodes: PropTypes.object.isRequired, path: PropTypes.array.isRequired, page: PropTypes.shape({ isFetching: PropTypes.bool, children: PropTypes.shape({ count: PropTypes.number, items: PropTypes.array, }), }).isRequired, onClose: PropTypes.func.isRequired, popPage: PropTypes.func.isRequired, pushPage: PropTypes.func.isRequired, }; export default ExplorerPanel;
src/dataTypes/RegExp.js
mrose/react-dump
import React from 'react'; import { Row, Table } from '../format'; export const RegExp = ( props ) => { const obj = props.obj || null const opts = props.opts || { expand:true , format:'html' , label:'RegExp' } let { label, expand } = opts return ( <Table className='reactdump reactdump-RegExp' label={label} cols='1' expand={expand}> <Row className='reactdump-label reactdump-RegExp' label={label} expand={expand} expandCells={expand}> {obj.toString()} </Row> </Table> ) };
src/pages/signup.js
guzmonne/mcp
import React from 'react' import SignupForm from '../components/signup/form.signup.js' import RowColXS12 from '../components/bootstrap/row.col-xs-12.js' import Logo from '../components/helpers/logo.helper.js' export default class Signup extends React.Component { render(){ return ( <div className="Signup"> <RowColXS12 className="text-center"> <Logo logo={this.props.location.query.client} className="Signup__logo"/> </RowColXS12> <RowColXS12> <SignupForm /> </RowColXS12> </div> ) } }
ReactNative/node_modules/react-navigation/src/views/Header/ModularHeaderBackButton.js
tahashahid/cloud-computing-2017
import React from 'react'; import { I18nManager, Image, Text, View, StyleSheet } from 'react-native'; import TouchableItem from '../TouchableItem'; class ModularHeaderBackButton extends React.PureComponent { static defaultProps = { tintColor: '#037aff', truncatedTitle: 'Back', // eslint-disable-next-line global-require buttonImage: require('../assets/back-icon.png'), }; state = {}; _onTextLayout = e => { if (this.state.initialTextWidth) { return; } this.setState({ initialTextWidth: e.nativeEvent.layout.x + e.nativeEvent.layout.width, }); }; render() { const { buttonImage, onPress, width, title, titleStyle, tintColor, truncatedTitle, } = this.props; const renderTruncated = this.state.initialTextWidth && width ? this.state.initialTextWidth > width : false; let backButtonTitle = renderTruncated ? truncatedTitle : title; // TODO: When we've sorted out measuring in the header, let's revisit this. // This is clearly a bad workaround. if (backButtonTitle && backButtonTitle.length > 8) { backButtonTitle = truncatedTitle; } const { ButtonContainerComponent, LabelContainerComponent } = this.props; return ( <TouchableItem accessibilityComponentType="button" accessibilityLabel={backButtonTitle} accessibilityTraits="button" testID="header-back" delayPressIn={0} onPress={onPress} style={styles.container} borderless > <View style={styles.container}> <ButtonContainerComponent> <Image style={[ styles.icon, !!title && styles.iconWithTitle, !!tintColor && { tintColor }, ]} source={buttonImage} /> </ButtonContainerComponent> {typeof backButtonTitle === 'string' && ( <LabelContainerComponent> <Text onLayout={this._onTextLayout} style={[ styles.title, !!tintColor && { color: tintColor }, titleStyle, ]} numberOfLines={1} > {backButtonTitle} </Text> </LabelContainerComponent> )} </View> </TouchableItem> ); } } const styles = StyleSheet.create({ container: { alignItems: 'center', flexDirection: 'row', backgroundColor: 'transparent', }, title: { fontSize: 17, paddingRight: 10, }, icon: { height: 21, width: 12, marginLeft: 9, marginRight: 22, marginVertical: 12, resizeMode: 'contain', transform: [{ scaleX: I18nManager.isRTL ? -1 : 1 }], }, iconWithTitle: { marginRight: 3, }, }); export default ModularHeaderBackButton;
springboot/GReact/src/main/resources/static/app/routes/forms/jcrop/containers/ApiPanelControls.js
ezsimple/java
import React from 'react' import OptionToggle from './../components/OptionToggle' import OptionRadio from './../components/OptionRadio' export default () =>( <div className="row" style={{ padding: '0 .75rem .5rem' }}> <fieldset className="col-md-4"> <legend>Selection properties</legend> <OptionToggle option="canDrag" label="Draggable"/> <OptionToggle option="canResize" label="Resizeable"/> <br/> <legend>Thumbnail</legend> <OptionToggle option="showThumbnail" label="Show"/> </fieldset> <fieldset className="col-md-4"> <legend>Aspect Ratio</legend> <OptionRadio group="aspectRatio" checked={true} options={{ aspectRatio: 0 }} label="None"/> <OptionRadio group="aspectRatio" options={{ aspectRatio: 1.4 }} label="Wide"/> <OptionRadio group="aspectRatio" options={{ aspectRatio: 0.8 }} label="Tall"/> <br/> <legend>Shading</legend> <OptionRadio group="shading" options={{ bgOpacity: .35, bgColor: 'black' }} label="Light"/> <OptionRadio group="shading" checked={true} options={{ bgOpacity: .55, bgColor: 'black' }} label="Medium"/> <OptionRadio group="shading" options={{ bgOpacity: .75, bgColor: 'black' }} label="Dark"/> </fieldset> <fieldset className="col-md-4"> <legend>New Selections</legend> <OptionRadio group="newSelections" options={{ allowSelect: false }} label="None"/> <OptionRadio group="newSelections" checked={true} options={{ allowSelect: true, multi: false }} label="Single"/> <OptionRadio group="newSelections" options={{ allowSelect: true, multi: true }} label="Multi"/> <br/> <legend>Test image</legend> <OptionRadio group="testImage" options={{ setImage: 'assets/img/superbox/superbox-full-24.jpg', bgOpacity: .6 }} label="Lego"/> <OptionRadio group="testImage" checked={true} options={{ setImage: 'assets/img/superbox/superbox-full-7.jpg', bgOpacity: .6 }} label="Breakdance"/> <OptionRadio group="testImage" options={{ setImage: 'assets/img/superbox/superbox-full-20.jpg', outerImage: 'assets/img/superbox/superbox-full-20-bw.jpg', bgOpacity: 1 }} label="Dragon Fly"/> </fieldset> </div> )
client/src/routes/index.js
OpenSecTre/sword
import React from 'react'; import { Route, IndexRoute } from 'react-router'; // NOTE: here we're making use of the `resolve.root` configuration // option in webpack, which allows us to specify import paths as if // they were from the root of the ~/src directory. This makes it // very easy to navigate to files regardless of how deeply nested // your current file is. import CoreLayout from 'layouts/CoreLayout/CoreLayout'; import ScanView from 'views/ScanView'; import StyleguideView from 'views/StyleguideView'; export default (store) => ( <Route path='/' component={CoreLayout}> <IndexRoute component={ScanView} /> <Route path='/styleguide' component={StyleguideView} /> </Route> );
lib/svg-icons/social/person-outline.js
checkraiser/material-ui2
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var SocialPersonOutline = React.createClass({ displayName: 'SocialPersonOutline', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z' }) ); } }); module.exports = SocialPersonOutline;
docs/pages/components/button-group.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'components/button-group'; const requireDemo = require.context('docs/src/pages/components/button-group', false, /\.(js|tsx)$/); const requireRaw = require.context( '!raw-loader!../../src/pages/components/button-group', false, /\.(js|md|tsx)$/, ); export default function Page({ demos, docs }) { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
blueocean-material-icons/src/js/components/svg-icons/editor/bubble-chart.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const EditorBubbleChart = (props) => ( <SvgIcon {...props}> <circle cx="7.2" cy="14.4" r="3.2"/><circle cx="14.8" cy="18" r="2"/><circle cx="15.2" cy="8.8" r="4.8"/> </SvgIcon> ); EditorBubbleChart.displayName = 'EditorBubbleChart'; EditorBubbleChart.muiName = 'SvgIcon'; export default EditorBubbleChart;
src/AppBar/AppBar.js
Lynx-Productions/OPeM
/*** * Copyright 2017 - present Lynx Productions * * 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. */ // @ts-check import React from 'react'; import { connect } from 'react-redux'; import MuiAppBar from 'material-ui/AppBar'; import { changeDrawer } from '../actions'; export const AppBar = ({ changeDrawer }) => ( <MuiAppBar title="OPeM" onLeftIconButtonTouchTap={() => changeDrawer(true)} /> ); const mapStateToProps = state => { return {}; }; const mapDispatchToProps = dispatch => { return { changeDrawer: open => { dispatch(changeDrawer(open)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(AppBar);
public/jspm_packages/npm/[email protected]/lib/svg-icons/image/filter-8.js
nayashooter/ES6_React-Bootstrap
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var ImageFilter8 = _react2.default.createClass({ displayName: 'ImageFilter8', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-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 16H7V3h14v14zm-8-2h2c1.1 0 2-.89 2-2v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7c0-1.11-.9-2-2-2h-2c-1.1 0-2 .89-2 2v1.5c0 .83.67 1.5 1.5 1.5-.83 0-1.5.67-1.5 1.5V13c0 1.11.9 2 2 2zm0-8h2v2h-2V7zm0 4h2v2h-2v-2z'})); } }); exports.default = ImageFilter8; module.exports = exports['default'];
fields/types/localfile/LocalFileField.js
BlakeRxxk/keystone
import Field from '../Field'; import React from 'react'; import { Button, FormField, FormInput, FormNote } from 'elemental'; module.exports = Field.create({ shouldCollapse () { return this.props.collapse && !this.hasExisting(); }, fileFieldNode () { return this.refs.fileField.getDOMNode(); }, changeFile () { this.refs.fileField.getDOMNode().click(); }, getFileSource () { if (this.hasLocal()) { return this.state.localSource; } else if (this.hasExisting()) { return this.props.value.url; } else { return null; } }, getFileURL () { if (!this.hasLocal() && this.hasExisting()) { return this.props.value.url; } }, undoRemove () { this.fileFieldNode().value = ''; this.setState({ removeExisting: false, localSource: null, origin: false, action: null }); }, fileChanged (event) {//eslint-disable-line no-unused-vars this.setState({ origin: 'local' }); }, removeFile (e) { var state = { localSource: null, origin: false }; if (this.hasLocal()) { this.fileFieldNode().value = ''; } else if (this.hasExisting()) { state.removeExisting = true; if (this.props.autoCleanup) { if (e.altKey) { state.action = 'reset'; } else { state.action = 'delete'; } } else { if (e.altKey) { state.action = 'delete'; } else { state.action = 'reset'; } } } this.setState(state); }, hasLocal () { return this.state.origin === 'local'; }, hasFile () { return this.hasExisting() || this.hasLocal(); }, hasExisting () { return !!this.props.value.filename; }, getFilename () { if (this.hasLocal()) { return this.fileFieldNode().value.split('\\').pop(); } else { return this.props.value.filename; } }, renderFileDetails (add) { var values = null; if (this.hasFile() && !this.state.removeExisting) { values = ( <div className='file-values'> <FormInput noedit>{this.getFilename()}</FormInput> </div> ); } return ( <div key={this.props.path + '_details'} className='file-details'> {values} {add} </div> ); }, renderAlert () { if (this.hasLocal()) { return ( <div className="file-values upload-queued"> <FormInput noedit>File selected - save to upload</FormInput> </div> ); } else if (this.state.origin === 'cloudinary') { return ( <div className="file-values select-queued"> <FormInput noedit>File selected from Cloudinary</FormInput> </div> ); } else if (this.state.removeExisting) { return ( <div className="file-values delete-queued"> <FormInput noedit>File {this.props.autoCleanup ? 'deleted' : 'removed'} - save to confirm</FormInput> </div> ); } else { return null; } }, renderClearButton () { if (this.state.removeExisting) { return ( <Button type="link" onClick={this.undoRemove}> Undo Remove </Button> ); } else { var clearText; if (this.hasLocal()) { clearText = 'Cancel Upload'; } else { clearText = (this.props.autoCleanup ? 'Delete File' : 'Remove File'); } return ( <Button type="link-cancel" onClick={this.removeFile}> {clearText} </Button> ); } }, renderFileField () { if (!this.shouldRenderField()) return null; return <input ref="fileField" type="file" name={this.props.paths.upload} className="field-upload" onChange={this.fileChanged} tabIndex="-1" />; }, renderFileAction () { if (!this.shouldRenderField()) return null; return <input type="hidden" name={this.props.paths.action} className="field-action" value={this.state.action} />; }, renderFileToolbar () { return ( <div key={this.props.path + '_toolbar'} className='file-toolbar'> <div className='u-float-left'> <Button onClick={this.changeFile}> {this.hasFile() ? 'Change' : 'Upload'} File </Button> {this.hasFile() && this.renderClearButton()} </div> </div> ); }, renderNote () { if (!this.props.note) return null; return <FormNote note={this.props.note} />; }, renderUI () { var container = []; var body = []; var hasFile = this.hasFile(); if (this.shouldRenderField()) { if (hasFile) { container.push(this.renderFileDetails(this.renderAlert())); } body.push(this.renderFileToolbar()); } else { if (hasFile) { container.push(this.renderFileDetails()); } else { container.push(<FormInput noedit>no file</FormInput>); } } return ( <FormField label={this.props.label} className="field-type-localfile"> {this.renderFileField()} {this.renderFileAction()} <div className="file-container">{container}</div> {body} {this.renderNote()} </FormField> ); } });
interfaces/global.js
simonfl3tcher/react-progressive-web-app
import React from 'react'; declare module CSSModule { declare var exports: { [key: string]: string }; } declare module OfflinePlugin { declare function install(): any; } declare interface System { static import: (module: string) => Promise<{ default: any, inc: number, }> }; declare module 'react-router' { declare interface ReactRouter extends React.Component<*, *, *> { IndexRoute: React.Component<*, *, *>; Link: React.Component<*, *, *>; Redirect: React.Component<*, *, *>; IndexRedirect: React.Component<*, *, *>; Route: React.Component<*, *, *>; Router: React.Component<*, *, *>; browserHistory: any; hashHistory: any; useRouterHistory: (historyFactory: Function) => (options: ?Object) => Object; match: Function; RouterContext: React.Component<*, *, *>; createRoutes: (routes: React$Element<*>) => Array<Object>; formatPattern: (pattern: string, params: Object) => string; withRouter: any; } declare var exports: ReactRouter; } declare module 'react-router/lib/PatternUtils' { declare var exports: any; } declare module 'history/lib/createBrowserHistory' { declare var exports: any; }
Server/app/assets/javascripts/components/NoteComponent.js
codemeow5/Carnival
import React from 'react'; export var NoteComponent = React.createClass({ render: function(){ return ( <div className="note note-info"> <p>{this.props.note}</p> </div> ); } }); export var NoteWithTitleComponent = React.createClass({ render: function(){ return ( <div className="note note-info"> <h4 className="block">{this.props.title}</h4> <p> {this.props.note} </p> </div> ); } }); export var AdvanceNoteComponent = React.createClass({ render: function(){ return ( <div className="alert alert-block alert-info fade in"> <button type="button" className="close" data-dismiss="alert"></button> <h4 className="alert-heading">{this.props.title || 'Information!'}</h4> <p> {this.props.content} </p> <p> <a className="btn purple" href=""> {this.props.button} </a> </p> </div> ); } });
ajax/libs/analytics.js/2.8.6/analytics.min.js
blairvanderhoof/cdnjs
(function umd(require){if("object"==typeof exports){module.exports=require("1")}else if("function"==typeof define&&define.amd){define(function(){return require("1")})}else{this["analytics"]=require("1")}})(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require}({1:[function(require,module,exports){var _analytics=window.analytics;var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("../bower.json").version;each(Integrations,function(name,Integration){analytics.use(Integration)})},{"analytics.js-integrations":2,"./analytics":3,each:4,"../bower.json":5}],2:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{each:4,"./integrations.js":6}],4:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:7}],7:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}if(val===null)return"null";if(val===undefined)return"undefined";if(val!==val)return"nan";if(val&&val.nodeType===1)return"element";val=val.valueOf?val.valueOf():Object.prototype.valueOf.apply(val);return typeof val}},{}],6:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/atatus"),require("./lib/autosend"),require("./lib/awesm"),require("./lib/bing-ads"),require("./lib/blueshift"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/extole"),require("./lib/facebook-conversion-tracking"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/fullstory"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/nudgespot"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/satismeter"),require("./lib/segmentio"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/userlike"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")]},{"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/atatus":13,"./lib/autosend":14,"./lib/awesm":15,"./lib/bing-ads":16,"./lib/blueshift":17,"./lib/bronto":18,"./lib/bugherd":19,"./lib/bugsnag":20,"./lib/chartbeat":21,"./lib/churnbee":22,"./lib/clicktale":23,"./lib/clicky":24,"./lib/comscore":25,"./lib/crazy-egg":26,"./lib/curebit":27,"./lib/customerio":28,"./lib/drip":29,"./lib/errorception":30,"./lib/evergage":31,"./lib/extole":32,"./lib/facebook-conversion-tracking":33,"./lib/foxmetrics":34,"./lib/frontleaf":35,"./lib/fullstory":36,"./lib/gauges":37,"./lib/get-satisfaction":38,"./lib/google-analytics":39,"./lib/google-tag-manager":40,"./lib/gosquared":41,"./lib/heap":42,"./lib/hellobar":43,"./lib/hittail":44,"./lib/hubspot":45,"./lib/improvely":46,"./lib/insidevault":47,"./lib/inspectlet":48,"./lib/intercom":49,"./lib/keen-io":50,"./lib/kenshoo":51,"./lib/kissmetrics":52,"./lib/klaviyo":53,"./lib/livechat":54,"./lib/lucky-orange":55,"./lib/lytics":56,"./lib/mixpanel":57,"./lib/mojn":58,"./lib/mouseflow":59,"./lib/mousestats":60,"./lib/navilytics":61,"./lib/nudgespot":62,"./lib/olark":63,"./lib/optimizely":64,"./lib/perfect-audience":65,"./lib/pingdom":66,"./lib/piwik":67,"./lib/preact":68,"./lib/qualaroo":69,"./lib/quantcast":70,"./lib/rollbar":71,"./lib/saasquatch":72,"./lib/satismeter":73,"./lib/segmentio":74,"./lib/sentry":75,"./lib/snapengage":76,"./lib/spinnakr":77,"./lib/tapstream":78,"./lib/trakio":79,"./lib/twitter-ads":80,"./lib/userlike":81,"./lib/uservoice":82,"./lib/vero":83,"./lib/visual-website-optimizer":84,"./lib/webengage":85,"./lib/woopra":86,"./lib/yandex-metrica":87}],8:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var del=require("obj-case").del;var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;var productId=track.id();var sku=track.sku();var customProps=track.properties();var data={};if(user.id())data.user_id=user.id();if(orderId)data.order_id=orderId;if(productId)data.product_id=productId;if(sku)data.sku=sku;if(total)data.adroll_conversion_value_in_dollars=total;del(customProps,"revenue");del(customProps,"total");del(customProps,"orderId");del(customProps,"id");del(customProps,"sku");if(!is.empty(customProps))data.adroll_custom_data=customProps;each(events,function(event){data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":88,"to-snake-case":89,"use-https":90,each:4,is:91,"obj-case":92}],88:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{bind:93,callback:94,clone:95,debug:96,defaults:97,"./protos":98,slug:99,"./statics":100}],93:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:101,"bind-all":102}],101:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],102:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:101,type:7}],94:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":103}],103:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],95:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],96:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":104,"./debug":105}],104:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],105:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],97:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],98:[function(require,module,exports){var loadScript=require("load-script");var loadIframe=require("load-iframe");var events=require("analytics-events");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var tick=require("next-tick");var after=require("after");var each=require("each");var type=require("type");var fmt=require("fmt");function noop(){}var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=window.onerror;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];if(!template)throw new Error(fmt('template "%s" not defined.',name));var attrs=render(template,locals);var fn=fn||noop;var self=this;var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,function(err){if(!err)return fn();self.debug('error loading "%s" error="%s"',self.name,err)});delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"load-script":106,"load-iframe":107,"analytics-events":108,"to-no-case":109,callback:94,emitter:110,"next-tick":103,after:111,each:112,type:113,fmt:114}],106:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":115,"next-tick":103,type:7}],115:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('script error "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)});el.attachEvent("onerror",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e||window.event;fn(err)})}},{}],107:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadIframe(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var iframe=document.createElement("iframe");iframe.src=options.src;iframe.width=options.width||1;iframe.height=options.height||1;iframe.style.display="none";if("function"==type(fn)){onload(iframe,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(iframe,firstScript)});return iframe}},{"script-onload":115,"next-tick":103,type:7}],108:[function(require,module,exports){module.exports={removedProduct:/^[ _]?removed[ _]?product[ _]?$/i,viewedProduct:/^[ _]?viewed[ _]?product[ _]?$/i,viewedProductCategory:/^[ _]?viewed[ _]?product[ _]?category[ _]?$/i,addedProduct:/^[ _]?added[ _]?product[ _]?$/i,completedOrder:/^[ _]?completed[ _]?order[ _]?$/i,startedOrder:/^[ _]?started[ _]?order[ _]?$/i,updatedOrder:/^[ _]?updated[ _]?order[ _]?$/i,refundedOrder:/^[ _]?refunded?[ _]?order[ _]?$/i,viewedProductDetails:/^[ _]?viewed[ _]?product[ _]?details?[ _]?$/i,clickedProduct:/^[ _]?clicked[ _]?product[ _]?$/i,viewedPromotion:/^[ _]?viewed[ _]?promotion?[ _]?$/i,clickedPromotion:/^[ _]?clicked[ _]?promotion?[ _]?$/i,viewedCheckoutStep:/^[ _]?viewed[ _]?checkout[ _]?step[ _]?$/i,completedCheckoutStep:/^[ _]?completed[ _]?checkout[ _]?step[ _]?$/i}},{}],109:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],110:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:116}],116:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],111:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],112:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:113,"component-type":113,"to-function":117}],113:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],117:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:118,"component-props":118}],118:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],114:[function(require,module,exports){var toString=window.JSON?JSON.stringify:function(_){return String(_)};module.exports=fmt;fmt.o=toString;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],99:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],100:[function(require,module,exports){var after=require("after");var domify=require("domify");var each=require("each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;if(!~str.indexOf(attr.name+"="))return;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:111,domify:119,each:112,emitter:110}],119:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.polyline=map.ellipse=map.polygon=map.circle=map.text=map.line=map.path=map.rect=map.g=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default; var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],89:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":120}],120:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":121}],121:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],90:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],91:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":122,type:7,"component-type":7}],122:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],92:[function(require,module,exports){var identity=function(_){return _};module.exports=multiple(find);module.exports.find=module.exports;module.exports.replace=function(obj,key,val,options){multiple(replace).call(this,obj,key,val,options);return obj};module.exports.del=function(obj,key,options){multiple(del).call(this,obj,key,null,options);return obj};function multiple(fn){return function(obj,path,val,options){var normalize=options&&isFunction(options.normalizer)?options.normalizer:defaultNormalize;path=normalize(path);var key;var finished=false;while(!finished)loop();function loop(){for(key in obj){var normalizedKey=normalize(key);if(0===path.indexOf(normalizedKey)){var temp=path.substr(normalizedKey.length);if(temp.charAt(0)==="."||temp.length===0){path=temp.substr(1);var child=obj[key];if(null==child){finished=true;return}if(!path.length){finished=true;return}obj=child;return}}}key=undefined;finished=true}if(!key)return;if(null==obj)return obj;return fn(obj,key,val)}}function find(obj,key){if(obj.hasOwnProperty(key))return obj[key]}function del(obj,key){if(obj.hasOwnProperty(key))delete obj[key];return obj}function replace(obj,key,val){if(obj.hasOwnProperty(key))obj[key]=val;return obj}function defaultNormalize(path){return path.replace(/[^a-zA-Z0-9\.]+/g,"").toLowerCase()}function isFunction(val){return typeof val==="function"}},{}],9:[function(require,module,exports){var integration=require("analytics.js-integration");var domify=require("domify");var each=require("each");var has=Object.prototype.hasOwnProperty;var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">').mapping("events");AdWords.prototype.initialize=function(){this.load(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=!!this.options.remarketing;var id=this.options.conversionId;var props={};window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_remarketing_only:remarketing})};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;each(events,function(label){var props=track.properties();delete props.revenue;window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:label,google_conversion_value:revenue,google_remarketing_only:false})})}},{"analytics.js-integration":88,domify:119,each:4}],10:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":88}],11:[function(require,module,exports){var integration=require("analytics.js-integration");var utm=require("utm-params");var top=require("top-domain");var umd="function"==typeof define&&define.amd;var src="//d24n15hnbwhuhn.cloudfront.net/libs/amplitude-2.1.0-min.js";var Amplitude=module.exports=integration("Amplitude").global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).option("trackUtmProperties",true).tag('<script src="'+src+'">');Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function a(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var i=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];for(var o=0;o<i.length;o++){a(i[o])}e.amplitude=r})(window,document);this.setDomain(window.location.href);window.amplitude.init(this.options.apiKey,null,{includeUtm:this.options.trackUtmProperties});var self=this;if(umd){window.require([src],function(amplitude){window.amplitude=amplitude;self.ready()});return}this.load(function(){self.ready()})};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();var revenue=track.revenue();window.amplitude.logEvent(event,props);if(revenue){window.amplitude.logRevenue(revenue,props.quantity,props.productId)}};Amplitude.prototype.setDomain=function(href){var domain=top(href);window.amplitude.setDomain(domain)};Amplitude.prototype.setDeviceId=function(deviceId){if(deviceId)window.amplitude.setDeviceId(deviceId)}},{"analytics.js-integration":88,"utm-params":123,"top-domain":124}],123:[function(require,module,exports){var parse=require("querystring").parse;module.exports=utm;function utm(query){if("?"==query.charAt(0))query=query.substring(1);var query=query.replace(/\?/g,"&");var params=parse(query);var param;var ret={};for(var key in params){if(~key.indexOf("utm_")){param=key.substr(4);if("campaign"==param)param="name";ret[param]=params[key]}}return ret}},{querystring:125}],125:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");var pattern=/(\w+)\[(\d+)\]/;exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=pattern.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:126,type:7}],126:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],124:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:127}],127:[function(require,module,exports){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)}};exports.isAbsolute=function(url){return 0==url.indexOf("//")||!!~url.indexOf("://")};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);var location=exports.parse(window.location.href);return url.hostname!==location.hostname||url.port!==location.port||url.protocol!==location.protocol};function port(protocol){switch(protocol){case"http:":return 80;case"https:":return 443;default:return location.port}}},{}],12:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"analytics.js-integration":88,"load-script":128,is:91}],128:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":115,"next-tick":103,type:7}],13:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Atatus=module.exports=integration("Atatus").global("atatus").option("apiKey","").tag('<script src="//www.atatus.com/atatus.js">');Atatus.prototype.initialize=function(page){var self=this;this.load(function(){window.atatus.config(self.options.apiKey).install();self.ready()})};Atatus.prototype.loaded=function(){return is.object(window.atatus)};Atatus.prototype.identify=function(identify){window.atatus.setCustomData({person:identify.traits()})}},{"analytics.js-integration":88,is:91}],14:[function(require,module,exports){var integration=require("analytics.js-integration");var Autosend=module.exports=integration("Autosend").global("_autosend").option("appKey","").tag('<script id="asnd-tracker" src="https://d2zjxodm1cz8d6.cloudfront.net/js/v1/autosend.js" data-auth-key="{{ appKey }}">');Autosend.prototype.initialize=function(page){window._autosend=window._autosend||[];(function(){var a,b,c;a=function(f){return function(){window._autosend.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track","cb"];for(c=0;c<b.length;c++){window._autosend[b[c]]=a(b[c])}})();this.load(this.ready)};Autosend.prototype.loaded=function(){return!!window._autosend};Autosend.prototype.identify=function(identify){var id=identify.userId();if(!id)return;var traits=identify.traits();traits.id=id;window._autosend.identify(traits)};Autosend.prototype.track=function(track){window._autosend.track(track.event())}},{"analytics.js-integration":88}],15:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":88,each:4}],16:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").global("uetq").option("tagId","").tag('<script src="//bat.bing.com/bat.js">');Bing.prototype.initialize=function(){window.uetq=window.uetq||[];var self=this;self.load(function(){var setup={ti:self.options.tagId,q:window.uetq};window.uetq=new UET(setup);self.ready()})};Bing.prototype.loaded=function(){return!!(window.uetq&&window.uetq.push!==Array.prototype.push)};Bing.prototype.page=function(){window.uetq.push("pageLoad")};Bing.prototype.track=function(track){var event={ea:"track",el:track.event()};if(track.category())event.ec=track.category();if(track.revenue())event.ev=track.revenue();window.uetq.push(event)}},{"analytics.js-integration":88,"on-body":129,domify:119,extend:130,bind:101,when:131,each:4}],129:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:112}],130:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],131:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:94}],17:[function(require,module,exports){var integration=require("analytics.js-integration");var Blueshift=module.exports=integration("Blueshift").global("blueshift").global("_blueshiftid").option("apiKey","").option("retarget",false).tag('<script src="https://cdn.getblueshift.com/blueshift.js">');Blueshift.prototype.initialize=function(page){window.blueshift=window.blueshift||[];window.blueshift.load=function(a){window._blueshiftid=a;var d=function(a){return function(){blueshift.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track","click","pageload","capture","retarget"];for(var f=0;f<e.length;f++)blueshift[e[f]]=d(e[f])};window.blueshift.load(this.options.apiKey);this.load(this.ready)};Blueshift.prototype.loaded=function(){return!!(window.blueshift&&window._blueshiftid)};Blueshift.prototype.page=function(page){if(this.options.retarget)window.blueshift.retarget();var properties=page.properties();properties._bsft_source="segment.com";window.blueshift.pageload(properties)};Blueshift.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits._bsft_source="segment.com";window.blueshift.identify(traits)};Blueshift.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits._bsft_source="segment.com";window.blueshift.track("group",traits)};Blueshift.prototype.track=function(track){var properties=track.properties();properties._bsft_source="segment.com";window.blueshift.track(track.event(),properties)}},{"analytics.js-integration":88}],18:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":88,facade:132,"load-pixel":133,querystring:134,each:4}],132:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":135,"./alias":136,"./group":137,"./identify":138,"./track":139,"./page":140,"./screen":141}],135:[function(require,module,exports){var traverse=require("isodate-traverse");var isEnabled=require("./is-enabled");var clone=require("./utils").clone;var type=require("./utils").type;var address=require("./address");var objCase=require("obj-case");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}address(Facade.prototype);Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.multi=function(path){return function(){var multi=this.proxy(path+"s");if("array"==type(multi))return multi;var one=this.proxy(path);if(one)one=[clone(one)];return one||[]}};Facade.one=function(path){return function(){var one=this.proxy(path);if(one)return one;var multi=this.proxy(path+"s");if("array"==type(multi))return multi[0]}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);return cloned}},{"isodate-traverse":142,"./is-enabled":143,"./utils":144,"./address":145,"obj-case":92,"new-date":146}],142:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:147,isodate:148,each:4}],147:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":122,type:7,"component-type":7}],148:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],143:[function(require,module,exports){var disabled={Salesforce:true};module.exports=function(integration){return!disabled[integration]}},{}],144:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone");exports.type=require("type")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component");exports.type=require("type-component")}},{inherit:149,clone:150,type:7}],149:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],150:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":7,type:7}],145:[function(require,module,exports){var get=require("obj-case");module.exports=function(proto){proto.zip=trait("postalCode","zip");proto.country=trait("country");proto.street=trait("street");proto.state=trait("state");proto.city=trait("city");function trait(a,b){return function(){var traits=this.traits();var props=this.properties?this.properties():{};return get(traits,"address."+a)||get(traits,a)||(b?get(traits,"address."+b):null)||(b?get(traits,b):null)||get(props,"address."+a)||get(props,a)||(b?get(props,"address."+b):null)||(b?get(props,b):null)}}}},{"obj-case":92}],146:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{is:151,isodate:148,"./milliseconds":152,"./seconds":153}],151:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":122,type:7}],152:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],153:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],136:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":144,"./facade":135}],137:[function(require,module,exports){var inherit=require("./utils").inherit;var address=require("./address");var isEmail=require("is-email");var newDate=require("new-date");var Facade=require("./facade");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var groupId=this.groupId();if(isEmail(groupId))return groupId};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.name=Facade.proxy("traits.name");Group.prototype.industry=Facade.proxy("traits.industry");Group.prototype.employees=Facade.proxy("traits.employees");Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}; }},{"./utils":144,"./address":145,"is-email":154,"new-date":146,"./facade":135}],154:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],138:[function(require,module,exports){var address=require("./address");var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var get=require("obj-case");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;var type=utils.type;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.age=function(){var date=this.birthday();var age=get(this.traits(),"age");if(null!=age)return age;if("date"!=type(date))return;var now=new Date;return now.getFullYear()-date.getFullYear()};Identify.prototype.avatar=function(){var traits=this.traits();return get(traits,"avatar")||get(traits,"photoUrl")||get(traits,"avatarUrl")};Identify.prototype.position=function(){var traits=this.traits();return get(traits,"position")||get(traits,"jobTitle")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.one("traits.website");Identify.prototype.websites=Facade.multi("traits.website");Identify.prototype.phone=Facade.one("traits.phone");Identify.prototype.phones=Facade.multi("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.gender=Facade.proxy("traits.gender");Identify.prototype.birthday=Facade.proxy("traits.birthday")},{"./address":145,"./facade":135,"is-email":154,"new-date":146,"./utils":144,"obj-case":92,trim:126}],139:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var type=require("./utils").type;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");var get=require("obj-case");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.discount=Facade.proxy("properties.discount");Track.prototype.description=Facade.proxy("properties.description");Track.prototype.plan=Facade.proxy("properties.plan");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=get(this.properties(),"subtotal");var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;if(n=this.discount())total+=n;return total};Track.prototype.products=function(){var props=this.properties();var products=get(props,"products");return"array"==type(products)?products:[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":144,"./facade":135,"./identify":138,"is-email":154,"obj-case":92}],140:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.title=Facade.proxy("properties.title");Page.prototype.path=Facade.proxy("properties.path");Page.prototype.url=Facade.proxy("properties.url");Page.prototype.referrer=function(){return this.proxy("properties.referrer")||this.proxy("context.referrer.url")};Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":144,"./facade":135,"./track":139}],141:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":144,"./page":140,"./track":139}],133:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:125,substitute:155}],155:[function(require,module,exports){module.exports=substitute;var type=Object.prototype.toString;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){switch(type.call(obj)){case"[object Object]":return null!=obj[prop]?obj[prop]:_;case"[object Array]":var val=obj.shift();return null!=val?val:_}})}},{}],134:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:126,type:7}],19:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":88,"next-tick":103}],20:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var umd="function"==typeof define&&define.amd;var src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js";var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="'+src+'">');Bugsnag.prototype.initialize=function(page){var self=this;if(umd){window.require([src],function(bugsnag){bugsnag.apiKey=self.options.apiKey;window.Bugsnag=bugsnag;self.ready()});return}this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":88,is:91,extend:130,"on-error":156}],156:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],21:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var category=page.category();if(category)window._sf_async_config.sections=category;var author=page.proxy("properties.author");if(author)window._sf_async_config.authors=author;var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":88,defaults:157,"on-body":129}],157:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],22:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":88,"global-queue":158,each:4}],158:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],23:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":159,domify:119,each:4,"analytics.js-integration":88,is:91,"use-https":90,"on-body":129}],159:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],24:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};var traits=identify.traits();var username=identify.username();var email=identify.email();var name=identify.name();if(username||email||name)traits.username=username||email||name;extend(window.clicky_custom.session,traits)};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:132,extend:130,"analytics.js-integration":88,is:91}],25:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE};Comscore.prototype.page=function(page){window.COMSCORE.beacon(this.options)}},{"analytics.js-integration":88,"use-https":90}],26:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":88}],27:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"analytics.js-integration":88,"global-queue":158,facade:132,throttle:160,"to-iso-string":161,clone:95,each:4,bind:101}],160:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],161:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],28:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!window._cio&&window._cio.push!==Array.prototype.push};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({createdAt:"created"});traits=alias(traits,{created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:162,"convert-dates":163,facade:132,"analytics.js-integration":88}],162:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:7,clone:150}],163:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:91,clone:95}],29:[function(require,module,exports){var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("_dc").global("_dcqi").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window._dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=track.cents();if(cents)props.value=cents;delete props.revenue;push("track",track.event(),props)};Drip.prototype.identify=function(identify){push("identify",identify.traits())}},{alias:162,"analytics.js-integration":88,is:91,"load-script":128,"global-queue":158}],30:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:130,"analytics.js-integration":88,"on-error":156,"global-queue":158}],31:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:4,"analytics.js-integration":88,"global-queue":158}],32:[function(require,module,exports){"use strict";var bind=require("bind");var domify=require("domify");var each=require("each");var extend=require("extend");var integration=require("analytics.js-integration");var json=require("json");var Extole=module.exports=integration("Extole").global("extole").option("clientId","").mapping("events").tag("main",'<script src="//tags.extole.com/{{ clientId }}/core.js">');Extole.prototype.initialize=function(){if(this.loaded())return this.ready();this.load("main",bind(this,this.ready))};Extole.prototype.loaded=function(){return!!window.extole};Extole.prototype.track=function(track){var user=this.analytics.user();var traits=user.traits();var userId=user.id();var email=traits.email;if(!userId&&!email){return this.debug("User must be identified before `#track` calls")}var event=track.event();var extoleEvents=this.events(event);if(!extoleEvents.length){return this.debug("No events found for %s",event)}each(extoleEvents,bind(this,function(extoleEvent){this._registerConversion(this._createConversionTag({type:extoleEvent,params:this._formatConversionParams(event,email,userId,track.properties())}))}))};Extole.prototype._registerConversion=function(conversionTag){if(window.extole.main&&window.extole.main.fireConversion){return window.extole.main.fireConversion(conversionTag)}if(window.extole.initializeGo){window.extole.initializeGo().andWhenItsReady(function(){window.extole.main.fireConversion(conversionTag)})}};Extole.prototype._formatConversionParams=function(event,email,userId,properties){var total;if(properties.total){total=properties.total;delete properties.total;properties["tag:cart_value"]=total}return extend({"tag:segment_event":event,e:email,partner_conversion_id:userId},properties)};Extole.prototype._createConversionTag=function(conversion){return domify('<script type="extole/conversion">'+json.stringify(conversion)+"</script>")}},{bind:101,domify:119,each:4,extend:130,"analytics.js-integration":88,json:164}],164:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":165}],165:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null; };String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],33:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Conversion Tracking").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})})}},{"analytics.js-integration":88,"global-queue":158,each:4}],34:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":158,"analytics.js-integration":88,facade:132,each:4}],35:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"analytics.js-integration":88,bind:101,when:131,is:91}],36:[function(require,module,exports){var foldl=require("foldl");var is=require("is");var camel=require("to-camel-case");var integration=require("analytics.js-integration");var FullStory=module.exports=integration("FullStory").option("org","").option("debug",false).tag('<script src="https://www.fullstory.com/s/fs.js"></script>');FullStory.prototype.initialize=function(){var self=this;window._fs_debug=this.options.debug;window._fs_host="www.fullstory.com";window._fs_org=this.options.org;(function(m,n,e,t,l,o,g,y){g=m[e]=function(a,b){g.q?g.q.push([a,b]):g._api(a,b)};g.q=[];g.identify=function(i,v){g(l,{uid:i});if(v)g(l,v)};g.setUserVars=function(v){FS(l,v)};g.setSessionVars=function(v){FS("session",v)};g.setPageVars=function(v){FS("page",v)};self.ready();self.load()})(window,document,"FS","script","user")};FullStory.prototype.loaded=function(){return!!window.FS};FullStory.prototype.identify=function(identify){var id=identify.userId()||identify.anonymousId();var traits=identify.traits({name:"displayName"});var newTraits=foldl(function(results,value,key){if(key!=="id")results[key==="displayName"||key==="email"?key:convert(key,value)]=value;return results},{},traits);window.FS.identify(String(id),newTraits)};function convert(trait,value){trait=camel(trait);if(is.string(value))return trait+="_str";if(isInt(value))return trait+="_int";if(isFloat(value))return trait+="_real";if(is.date(value))return trait+="_date";if(is.boolean(value))return trait+="_bool"}function isFloat(n){return n===+n&&n!==(n|0)}function isInt(n){return n===+n&&n===(n|0)}},{foldl:166,is:91,"to-camel-case":167,"analytics.js-integration":88}],166:[function(require,module,exports){"use strict";var each=require("each");var foldl=function foldl(iterator,accumulator,collection){if(typeof iterator!=="function"){throw new TypeError("Expected a function but received a "+typeof iterator)}each(function(val,i,collection){accumulator=iterator(accumulator,val,i,collection)},collection);return accumulator};module.exports=foldl},{each:168}],168:[function(require,module,exports){"use strict";var keys=require("keys");var objToString=Object.prototype.toString;var isNumber=function isNumber(val){var type=typeof val;return type==="number"||type==="object"&&objToString.call(val)==="[object Number]"};var isArray=typeof Array.isArray==="function"?Array.isArray:function isArray(val){return objToString.call(val)==="[object Array]"};var isArrayLike=function isArrayLike(val){return val!=null&&(isArray(val)||val!=="function"&&isNumber(val.length))};var arrayEach=function arrayEach(iterator,array){for(var i=0;i<array.length;i+=1){if(iterator(array[i],i,array)===false){break}}};var baseEach=function baseEach(iterator,object){var ks=keys(object);for(var i=0;i<ks.length;i+=1){if(iterator(object[ks[i]],ks[i],object)===false){break}}};var each=function each(iterator,collection){return(isArrayLike(collection)?arrayEach:baseEach).call(this,iterator,collection)};module.exports=each},{keys:169}],169:[function(require,module,exports){"use strict";var strCharAt=String.prototype.charAt;var charAt=function(str,index){return strCharAt.call(str,index)};var hop=Object.prototype.hasOwnProperty;var toStr=Object.prototype.toString;var has=function has(context,prop){return hop.call(context,prop)};var isString=function isString(val){return toStr.call(val)==="[object String]"};var isArrayLike=function isArrayLike(val){return val!=null&&(typeof val!=="function"&&typeof val.length==="number")};var indexKeys=function indexKeys(target,pred){pred=pred||has;var results=[];for(var i=0,len=target.length;i<len;i+=1){if(pred(target,i)){results.push(String(i))}}return results};var objectKeys=function objectKeys(target,pred){pred=pred||has;var results=[];for(var key in target){if(pred(target,key)){results.push(String(key))}}return results};module.exports=function keys(source){if(source==null){return[]}if(isString(source)){return indexKeys(source,charAt)}if(isArrayLike(source)){return indexKeys(source,has)}return objectKeys(source)}},{}],167:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":120}],37:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":88,"global-queue":158}],38:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":88,"on-body":129}],39:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var defaults=require("defaults");var load=require("load-script");var keys=require("object").keys;var select=require("select");var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","auto").option("doubleClick",false).option("enhancedEcommerce",false).option("enhancedLinkAttribution",false).option("nonInteraction",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(integration.options.classic){integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic}else if(integration.options.enhancedEcommerce){integration.viewedProduct=integration.viewedProductEnhanced;integration.clickedProduct=integration.clickedProductEnhanced;integration.addedProduct=integration.addedProductEnhanced;integration.removedProduct=integration.removedProductEnhanced;integration.startedOrder=integration.startedOrderEnhanced;integration.viewedCheckoutStep=integration.viewedCheckoutStepEnhanced;integration.completedCheckoutStep=integration.completedCheckoutStepEnhanced;integration.updatedOrder=integration.updatedOrderEnhanced;integration.completedOrder=integration.completedOrderEnhanced;integration.refundedOrder=integration.refundedOrderEnhanced;integration.viewedPromotion=integration.viewedPromotionEnhanced;integration.clickedPromotion=integration.clickedPromotionEnhanced}});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();if(window.location.hostname==="localhost")opts.domain="none";window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","userId",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var campaign=page.proxy("context.campaign")||{};var pageview={};var track;this._category=category;pageview.page=path(props,this.options);pageview.title=name||props.title;pageview.location=props.url;if(campaign.name)pageview.campaignName=campaign.name;if(campaign.source)pageview.campaignSource=campaign.source;if(campaign.medium)pageview.campaignMedium=campaign.medium;if(campaign.content)pageview.campaignContent=campaign.content;if(campaign.term)pageview.campaignKeyword=campaign.term;var custom=metrics(props,opts);if(length(custom))window.ga("set",custom);window.ga("send","pageview",pageview);if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{nonInteraction:1})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{nonInteraction:1})}};GA.prototype.identify=function(identify){var opts=this.options;if(opts.sendUserId&&identify.userId()){window.ga("set","userId",identify.userId())}var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom)};GA.prototype.track=function(track,options){var contextOpts=track.options(this.name);var interfaceOpts=this.options;var opts=defaults(options||{},contextOpts);opts=defaults(opts,interfaceOpts);var props=track.properties();var campaign=track.proxy("context.campaign")||{};var custom=metrics(props,interfaceOpts);if(length(custom))window.ga("set",custom);var payload={eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:!!(props.nonInteraction||opts.nonInteraction)};if(campaign.name)payload.campaignName=campaign.name;if(campaign.source)payload.campaignSource=campaign.source;if(campaign.medium)payload.campaignMedium=campaign.medium;if(campaign.content)payload.campaignContent=campaign.content;if(campaign.term)payload.campaignKeyword=campaign.term;window.ga("send","event",payload)};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId,currency:track.currency()});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId,currency:track.currency()})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{nonInteraction:1})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{nonInteraction:1})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var nonInteraction=!!(props.nonInteraction||opts.nonInteraction);push("_trackEvent",category,event,label,value,nonInteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();var currency=track.currency();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_set","currencyCode",currency);push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name)||obj[name];if(null==value)continue;ret[key]=value}return ret}GA.prototype.loadEnhancedEcommerce=function(track){if(!this.enhancedEcommerceLoaded){window.ga("require","ec");this.enhancedEcommerceLoaded=true}window.ga("set","&cu",track.currency())};GA.prototype.pushEnhancedEcommerce=function(track){ga("send","event",track.category()||"EnhancedEcommerce",track.event(),{nonInteraction:1})};GA.prototype.startedOrderEnhanced=function(track){this.viewedCheckoutStep(track)};GA.prototype.updatedOrderEnhanced=function(track){this.startedOrderEnhanced(track)};GA.prototype.viewedCheckoutStepEnhanced=function(track){var products=track.products();var props=track.properties();var options=extractCheckoutOptions(props);this.loadEnhancedEcommerce(track);each(products,function(product){var trackTemp=new Track({properties:product});enhancedEcommerceTrackProduct(trackTemp)});window.ga("ec:setAction","checkout",{step:props.step||1,option:options||undefined});this.pushEnhancedEcommerce(track)};GA.prototype.completedCheckoutStepEnhanced=function(track){var props=track.properties();var options=extractCheckoutOptions(props);if(!props.step||!options)return;this.loadEnhancedEcommerce(track);window.ga("ec:setAction","checkout_option",{step:props.step||1,option:options});window.ga("send","event","Checkout","Option")};GA.prototype.completedOrderEnhanced=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;this.loadEnhancedEcommerce(track);each(products,function(product){var track=new Track({properties:product});enhancedEcommerceTrackProduct(track)});window.ga("ec:setAction","purchase",{id:orderId,affiliation:props.affiliation,revenue:total,tax:track.tax(),shipping:track.shipping(),coupon:track.coupon()});this.pushEnhancedEcommerce(track)};GA.prototype.refundedOrderEnhanced=function(track){var orderId=track.orderId();var products=track.products();if(!orderId)return;this.loadEnhancedEcommerce(track);each(products,function(product){var track=new Track({properties:product});window.ga("ec:addProduct",{id:track.id()||track.sku(),quantity:track.quantity()})});window.ga("ec:setAction","refund",{id:orderId});this.pushEnhancedEcommerce(track)};GA.prototype.addedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"add");this.pushEnhancedEcommerce(track)};GA.prototype.removedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"remove");this.pushEnhancedEcommerce(track)};GA.prototype.viewedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"detail");this.pushEnhancedEcommerce(track)};GA.prototype.clickedProductEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"click",{list:props.list});this.pushEnhancedEcommerce(track)};GA.prototype.viewedPromotionEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);window.ga("ec:addPromo",{id:track.id(),name:track.name(),creative:props.creative,position:props.position});this.pushEnhancedEcommerce(track)};GA.prototype.clickedPromotionEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);window.ga("ec:addPromo",{id:track.id(),name:track.name(),creative:props.creative,position:props.position});ga("ec:setAction","promo_click",{});this.pushEnhancedEcommerce(track)};function enhancedEcommerceTrackProduct(track){var props=track.properties();window.ga("ec:addProduct",{id:track.id()||track.sku(),name:track.name(),category:track.category(),quantity:track.quantity(),price:track.price(),brand:props.brand,variant:props.variant})}function enhancedEcommerceProductAction(track,action,data){enhancedEcommerceTrackProduct(track);window.ga("ec:setAction",action,data||{})}function extractCheckoutOptions(props){var options=[props.paymentMethod,props.shippingMethod];var valid=select(options,function(e){return e});return valid.length>0?valid.join(", "):null}},{"analytics.js-integration":88,"global-queue":158,object:170,canonical:171,"use-https":90,facade:132,callback:94,defaults:157,"load-script":128,select:172,"obj-case":92,each:4,type:113,url:173,is:91}],170:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],171:[function(require,module,exports){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],172:[function(require,module,exports){var toFunction=require("to-function");module.exports=function(arr,fn){var ret=[];fn=toFunction(fn);for(var i=0;i<arr.length;++i){if(fn(arr[i],i)){ret.push(arr[i])}}return ret}},{"to-function":174}],174:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:118,"component-props":118}],173:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],40:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":158,"analytics.js-integration":88}],41:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify; var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var is=require("is");var pick=require("pick");var omit=require("omit");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({createdAt:"created_at",firstName:"first_name",lastName:"last_name",title:"company_position",industry:"company_industry"});var specialKeys=["id","email","name","first_name","last_name","username","description","avatar","phone","created_at","company_name","company_size","company_position","company_industry"];var props=pick.apply(null,[traits].concat(specialKeys));props.custom=omit(specialKeys,traits);var id=identify.userId();if(id){push("identify",id,props)}else{push("properties",props)}var email=identify.email();var username=identify.username();var name=email||username||id;if(name)push("set","visitorName",name)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":88,facade:132,callback:94,"load-script":128,"on-body":129,each:4,is:91,pick:175,omit:176}],175:[function(require,module,exports){module.exports=pick;function pick(obj){var keys=[].slice.call(arguments,1);var ret={};for(var i=0,key;key=keys[i];i++){if(key in obj)ret[key]=obj[key]}return ret}},{}],176:[function(require,module,exports){module.exports=omit;function omit(keys,object){var ret={};for(var item in object){ret[item]=object[item]}for(var i=0;i<keys.length;i++){delete ret[keys[i]]}return ret}},{}],42:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").global("heap").option("appId","").tag('<script src="//cdn.heapanalytics.com/js/heap-{{ appId }}.js">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(appid,config){window.heap.appid=appid;window.heap.config=config;var methodFactory=function(type){return function(){heap.push([type].concat(Array.prototype.slice.call(arguments,0)))}};var methods=["clearEventProperties","identify","setEventProperties","track","unsetEventProperty"];for(var i=0;i<methods.length;i++){heap[methods[i]]=methodFactory(methods[i])}};window.heap.load(this.options.appId);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits({email:"_email"});var id=identify.userId();if(id)traits.handle=id;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":88,alias:162}],43:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":88}],44:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":88,is:91}],45:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":88,"global-queue":158,"convert-dates":163}],46:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":88,alias:162}],47:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);var userId=this.analytics.user().id();if(userId)push("setUserId",userId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.identify=function(identify){push("setUserId",identify.userId())};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.events(track.event());var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.id()||"";each(events,function(event){if(event!="sale"){push("trackEvent",event,value,eventId)}})}},{"analytics.js-integration":88,"global-queue":158,facade:132,each:4,is:91}],48:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//cdn.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!(window.__insp_&&window.__insp)};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())};Inspectlet.prototype.page=function(){push("virtualPage")}},{"analytics.js-integration":88,"global-queue":158,alias:162,clone:95}],49:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var del=require("obj-case").del;var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(created){del(traits,"created");del(traits,"createdAt");traits.created_at=created}if(companyCreated){del(traits.company,"created");del(traits.company,"createdAt");traits.company.created_at=companyCreated}traits=convertDates(traits,formatDate);if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();props=alias(props,{createdAt:"created"});props=alias(props,{created:"created_at"});var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":88,"convert-dates":163,defaults:157,"obj-case":92,"is-email":154,"load-script":128,"is-empty":122,alias:162,each:4,when:131,is:91}],50:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("ipAddon",false).option("uaAddon",false).option("urlAddon",false).option("referrerAddon",false).option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');Keen.prototype.initialize=function(){var options=this.options;!function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window);this.client=new window.Keen({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});var lib=this.options.readKey?"keen":"keen-tracker";this.load({lib:lib},this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.prototype.configure)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};if(id)user.userId=id;if(traits)user.traits=traits;var props={user:user};this.addons(props,identify);this.client.setGlobalProperties(function(){return clone(props)})};Keen.prototype.track=function(track){var props=track.properties();this.addons(props,track);this.client.addEvent(track.event(),props)};Keen.prototype.addons=function(obj,msg){var options=this.options;var addons=[];if(options.ipAddon){addons.push({name:"keen:ip_to_geo",input:{ip:"ip_address"},output:"ip_geo_info"});obj.ip_address="${keen.ip}"}if(options.uaAddon){addons.push({name:"keen:ua_parser",input:{ua_string:"user_agent"},output:"parsed_user_agent"});obj.user_agent="${keen.user_agent}"}if(options.urlAddon){addons.push({name:"keen:url_parser",input:{url:"page_url"},output:"parsed_page_url"});obj.page_url=document.location.href}if(options.referrerAddon){addons.push({name:"keen:referrer_parser",input:{referrer_url:"referrer_url",page_url:"page_url"},output:"referrer_info"});obj.referrer_url=document.referrer;obj.page_url=document.location.href}obj.keen={timestamp:msg.timestamp(),addons:addons}}},{"analytics.js-integration":88,clone:95}],51:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":88,indexof:116,is:91}],52:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("library",'<script src="//scripts.kissmetrics.com/{{ apiKey }}.2.js">');exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});this.load("library",function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"analytics.js-integration":88,"global-queue":158,facade:132,alias:162,each:4,is:91}],53:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":88,"global-queue":158,"next-tick":103,alias:162}],54:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});window.__lc=clone(this.options);window.__lc.visitor={name:identify.name(),email:identify.email()};this.load(function(){when(function(){return self.loaded()},self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":88,clone:95,each:4,facade:132,when:131}],55:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":88,facade:132,"use-https":90}],56:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":88,alias:162}],57:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var is=require("is");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var some=require("some");var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("crossSubdomainCookie",false).option("secureCookie",false).option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js">');var optionsAliases={cookieName:"cookie_name",crossSubdomainCookie:"cross_subdomain_cookie",secureCookie:"secure_cookie"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(dates(traits,iso));if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;for(var key in props){var val=props[key];if(is.array(val)&&some(val,is.object))props[key]=val.length}if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:162,clone:95,"convert-dates":163,"analytics.js-integration":88,is:91,"to-iso-string":161,indexof:116,"obj-case":92,some:177}],177:[function(require,module,exports){var some=[].some;module.exports=function(arr,fn){if(some)return some.call(arr,fn);for(var i=0,l=arr.length;i<l;++i){if(fn(arr[i],i))return true}return false}},{}],58:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/identify.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"analytics.js-integration":88,bind:101,when:131,is:91}],59:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":158,"analytics.js-integration":88,each:4}],60:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":88,"use-https":90,each:4,is:91}],61:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":88,"global-queue":158}],62:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Identify=require("facade").Identify;var Nudgespot=module.exports=integration("Nudgespot").assumesPageview().option("apiKey","").global("nudgespot").tag('<script id="nudgespot" src="//cdn.nudgespot.com/nudgespot.js">');Nudgespot.prototype.initialize=function(page){window.nudgespot=window.nudgespot||[];window.nudgespot.init=function(n,t){function f(n,m){var a=m.split(".");2==a.length&&(n=n[a[0]],m=a[1]);n[m]=function(){n.push([m].concat(Array.prototype.slice.call(arguments,0)))}}n._version=.1;n._globals=[t];n.people=n.people||[];n.params=n.params||[];m="track register unregister identify set_config people.delete people.create people.update people.create_property people.tag people.remove_Tag".split(" "); for(var i=0;i<m.length;i++)f(n,m[i])};window.nudgespot.init(window.nudgespot,this.options.apiKey);this.load(this.ready)};Nudgespot.prototype.loaded=function(){return!!window.nudgespot&&window.nudgespot.push!==Array.prototype.push};Nudgespot.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({createdAt:"created"});traits=alias(traits,{created:"created_at"});window.nudgespot.identify(identify.userId(),traits)};Nudgespot.prototype.track=function(track){var properties=track.properties();window.nudgespot.track(track.event(),properties)}},{"analytics.js-integration":88,alias:162,facade:132}],63:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId)api("chat.setOperatorGroup",{group:groupId});api("box.onExpand",function(){self._open=true});api("box.onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;name=name?name+" page":props.url;this.notify("looking at "+name)};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();if(traits)api("visitor.updateCustomFields",traits);if(email)api("visitor.updateEmailAddress",{emailAddress:email});if(phone)api("visitor.updatePhoneNumber",{phoneNumber:phone});if(name)api("visitor.updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)api("chat.updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track)return;this.notify('visitor triggered "'+track.event()+'"')};Olark.prototype.notify=function(message){if(!this._open)return;message=message.toLowerCase();api("visitor.getDetails",function(data){if(!data||!data.isConversing)return;api("chat.sendNotificationToOperator",{body:message})})};function api(action,value){window.olark("api."+action,value)}},{"analytics.js-integration":88,"use-https":90,"next-tick":103}],64:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data||!data.state)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"analytics.js-integration":88,"global-queue":158,callback:94,"next-tick":103,bind:101,each:4}],65:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_pq");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pq").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pq=window._pq||[];this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pq&&window._pq.push)};PerfectAudience.prototype.track=function(track){var total=track.total()||track.revenue();var orderId=track.orderId();var props={};var sendProps=false;if(total){props.revenue=total;sendProps=true}if(orderId){props.orderId=orderId;sendProps=true}if(!sendProps)return push("track",track.event());return push("track",track.event(),props)};PerfectAudience.prototype.viewedProduct=function(track){var product=track.sku();push("track",track.event());push("trackProduct",product)};PerfectAudience.prototype.completedOrder=function(track){var total=track.total()||track.revenue();var orderId=track.orderId();var props={};if(total)props.revenue=total;if(orderId)props.orderId=orderId;push("track",track.event(),props)}},{"analytics.js-integration":88,"global-queue":158}],66:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":88,"global-queue":158,"load-date":159}],67:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var is=require("is");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").option("customVariableLimit",5).mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue();var category=track.category()||"All";var action=track.event();var name=track.proxy("properties.name")||track.proxy("properties.label");var value=track.value()||track.revenue();var options=track.options("Piwik");var customVariables=options.customVars||options.cvar;if(!is.object(customVariables)){customVariables={}}for(var i=1;i<=this.options.customVariableLimit;i+=1){if(customVariables[i]){push("setCustomVariable",i.toString(),customVariables[i][0],customVariables[i][1],"page")}}each(goals,function(goal){push("trackGoal",goal,revenue)});push("trackEvent",category,action,name,value)}},{"analytics.js-integration":88,"global-queue":158,each:4,is:91}],68:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_preactq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_preactq").global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/preact-4.1.min.js">');Preact.prototype.initialize=function(page){window._preactq=window._preactq||[];window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._preactq&&window._preactq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":88,"convert-dates":163,"global-queue":158,alias:162}],69:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"analytics.js-integration":88,"global-queue":158,facade:132,bind:101,when:131}],70:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var is=require("is");var reduce=require("reduce");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this._labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var customLabels=page.proxy("properties.label");var labels=this._labels("page",category,name,customLabels);var settings={event:"refresh",labels:labels,qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var orderId=track.orderId();var customLabels=track.proxy("properties.label");var labels=this._labels("event",name,customLabels);var settings={event:"click",labels:labels,qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(orderId)settings.orderid=orderId;if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var customLabels=track.proxy("properties.label");var labels=this._labels("event",name,customLabels);var category=track.category();var repeat=track.proxy("properties.repeat");if(this.options.advertise&&category){labels+=","+this._labels("pcat",category)}if("boolean"==typeof repeat){labels+=",_fp.customer."+(repeat?"repeat":"new")}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype._labels=function(type){var args=Array.prototype.slice.call(arguments,1);var advertise=this.options.advertise;if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;var separator=advertise?" ":".";var ret=reduce(args,function(ret,arg){if(arg!=null){ret.push(String(arg).replace(/, /g,","))}return ret},[]).join(separator);return[type,ret].join(".")}},{"global-queue":158,"analytics.js-integration":88,"use-https":90,is:91,reduce:178}],178:[function(require,module,exports){module.exports=function(arr,fn,initial){var idx=0;var len=arr.length;var curr=arguments.length==3?initial:arr[idx++];while(idx<len){curr=fn.call(null,curr,arr[idx],++idx,arr)}return curr}},{}],71:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a,b){function c(b){this.shimId=++h,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function d(b,c,d){a._rollbarWrappedError&&(d[4]||(d[4]=a._rollbarWrappedError),d[5]||(d[5]=a._rollbarWrappedError._rollbarContext),a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function e(b){var d=c;return g(function(){if(this.notifier)return this.notifier[b].apply(this.notifier,arguments);var c=this,e="scope"===b;e&&(c=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:c,method:b,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?c:void 0})}function f(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b&&b._wrapped?b._wrapped:b,c)}}}function g(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var h=0;c.init=function(a,b){var e=b.globalAlias||"Rollbar";if("object"==typeof a[e])return a[e];a._rollbarShimQueue=[],a._rollbarWrappedError=null,b=b||{};var h=new c;return g(function(){if(h.configure(b),b.captureUncaught){var c=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);d(h,c,a)};var g,i,j="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(g=0;g<j.length;++g)i=j[g],a[i]&&a[i].prototype&&f(h,a[i].prototype)}return a[e]=h,h},h.logger)()},c.prototype.loadFull=function(a,b,c,d,e){var f=g(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=g(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}"function"==typeof e&&e(b)},this.logger);g(function(){c?f():a.addEventListener?a.addEventListener("load",f,!1):a.attachEvent("onload",f)},this.logger)()},c.prototype.wrap=function(b,c){try{var d;if(d="function"==typeof c?c:function(){return c||{}},"function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw c._rollbarContext=d(),c._rollbarContext._wrappedSource=b.toString(),a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var e in b)b.hasOwnProperty(e)&&(b._wrapped[e]=b[e])}return b._wrapped}catch(f){return b}};for(var i="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),j=0;j<i.length;++j)c.prototype[i[j]]=e(i[j]);var k="//d37gvrvc0wt4s1.cloudfront.net/js/v1.1/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||k;var l=c.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"analytics.js-integration":88,extend:130,is:91}],72:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").option("referralImage","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var paymentProviderId=identify.proxy("traits.paymentProviderId");var accountStatus=identify.proxy("traits.accountStatus");var referralCode=identify.proxy("traits.referralCode");var image=identify.proxy("traits.referralImage")||this.options.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(paymentProviderId)init.payment_provider_id=paymentProviderId;if(init.payment_provider_id=="null")init.payment_provider_id=null;if(accountStatus)init.account_status=accountStatus;if(referralCode)init.referral_code=referralCode;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()};SaaSquatch.prototype.group=function(group){var sqh=window._sqh;var props=group.properties();var id=group.groupId();var image=group.proxy("traits.referralImage")||this.options.referralImage;var opts=group.options(this.name);if(this.called)return;var init={tenant_alias:this.options.tenantAlias,account_id:id};if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"analytics.js-integration":88}],73:[function(require,module,exports){var integration=require("analytics.js-integration");var when=require("when");var SatisMeter=module.exports=integration("SatisMeter").global("satismeter").option("token","").tag('<script src="https://app.satismeter.com/satismeter.js">');SatisMeter.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};SatisMeter.prototype.loaded=function(){return!!window.satismeter};SatisMeter.prototype.identify=function(identify){var traits=identify.traits();traits.token=this.options.token;traits.user={id:identify.userId()};if(identify.name()){traits.user.name=identify.name()}if(identify.email()){traits.user.email=identify.email()}if(identify.created()){traits.user.signUpDate=identify.created().toISOString()}delete traits.id;delete traits.email;delete traits.name;delete traits.created;window.satismeter(traits)}},{"analytics.js-integration":88,when:131}],74:[function(require,module,exports){var integration=require("analytics.js-integration");var localstorage=require("store");var protocol=require("protocol");var utm=require("utm-params");var ads=require("ad-params");var send=require("send-json");var cookie=require("cookie");var clone=require("clone");var uuid=require("uuid");var top=require("top-domain");var extend=require("extend");var json=require("segmentio/[email protected]");var options={maxage:31536e6,secure:false,path:"/"};var Segment=exports=module.exports=integration("Segment.io").option("apiKey","");exports.storage=function(){return"file:"==protocol()||"chrome-extension:"==protocol()?localstorage:cookie};exports.global=window;Segment.prototype.initialize=function(page){var self=this;this.ready();this.analytics.on("invoke",function(msg){var action=msg.action();var listener="on"+msg.action();self.debug("%s %o",action,msg);if(self[listener])self[listener](msg);self.ready()})};Segment.prototype.loaded=function(){return true};Segment.prototype.onpage=function(page){this.send("/p",page.json())};Segment.prototype.onidentify=function(identify){this.send("/i",identify.json())};Segment.prototype.ongroup=function(group){this.send("/g",group.json())};Segment.prototype.ontrack=function(track){var json=track.json();delete json.traits;this.send("/t",json)};Segment.prototype.onalias=function(alias){var json=alias.json();var user=this.analytics.user();json.previousId=json.previousId||json.from||user.id()||user.anonymousId();json.userId=json.userId||json.to;delete json.from;delete json.to;this.send("/a",json)};Segment.prototype.normalize=function(msg){this.debug("normalize %o",msg);var user=this.analytics.user();var global=exports.global;var query=global.location.search;var ctx=msg.context=msg.context||msg.options||{};delete msg.options;msg.writeKey=this.options.apiKey;ctx.userAgent=navigator.userAgent;if(!ctx.library)ctx.library={name:"analytics.js",version:this.analytics.VERSION};if(query)ctx.campaign=utm(query);this.referrerId(query,ctx);msg.userId=msg.userId||user.id();msg.anonymousId=user.anonymousId();msg.messageId=uuid();msg.sentAt=new Date;this.debug("normalized %o",msg);return msg};Segment.prototype.send=function(path,msg,fn){var url=scheme()+"//api.segment.io/v1"+path;var headers={"Content-Type":"text/plain"};var fn=fn||noop;var self=this;msg=this.normalize(msg);send(url,msg,headers,function(err,res){self.debug("sent %O, received %O",msg,arguments);if(err)return fn(err);res.url=url;fn(null,res)})};Segment.prototype.cookie=function(name,val){var store=Segment.storage();if(arguments.length===1)return store(name);var global=exports.global;var href=global.location.href;var domain="."+top(href);if("."==domain)domain="";this.debug("store domain %s -> %s",href,domain);var opts=clone(options);opts.domain=domain;this.debug("store %s, %s, %o",name,val,opts);store(name,val,opts);if(store(name))return;delete opts.domain;this.debug("fallback store %s, %s, %o",name,val,opts);store(name,val,opts)};Segment.prototype.referrerId=function(query,ctx){var stored=this.cookie("s:context.referrer");var ad;if(stored)stored=json.parse(stored);if(query)ad=ads(query);ad=ad||stored;if(!ad)return;ctx.referrer=extend(ctx.referrer||{},ad);this.cookie("s:context.referrer",json.stringify(ad))};function scheme(){return"http:"==protocol()?"http:":"https:"}function noop(){}},{"analytics.js-integration":88,store:179,protocol:180,"utm-params":123,"ad-params":181,"send-json":182,cookie:183,clone:95,uuid:184,"top-domain":124,extend:130,"segmentio/[email protected]":164}],179:[function(require,module,exports){var unserialize=require("unserialize");var each=require("each");var storage;try{storage=window.localStorage}catch(e){storage=null}module.exports=store;function store(key,value){var length=arguments.length;if(0==length)return all();if(2<=length)return set(key,value);if(1!=length)return;if(null==key)return storage.clear();if("string"==typeof key)return get(key);if("object"==typeof key)return each(key,set)}store.supported=!!storage;function set(key,val){return null==val?storage.removeItem(key):storage.setItem(key,JSON.stringify(val))}function get(key){return unserialize(storage.getItem(key))}function all(){var len=storage.length;var ret={};var key;while(0<=--len){key=storage.key(len);ret[key]=get(key)}return ret}},{unserialize:185,each:112}],185:[function(require,module,exports){module.exports=function(val){try{return JSON.parse(val)}catch(e){return val||undefined}}},{}],180:[function(require,module,exports){var define=Object.defineProperty;var initialProtocol=window.location.protocol;var mockedProtocol;module.exports=function(protocol){if(arguments.length===0)return get();else return set(protocol)};module.exports.http=function(){set("http:")};module.exports.https=function(){set("https:")};module.exports.reset=function(){set(initialProtocol)};function get(){return mockedProtocol||window.location.protocol}function set(protocol){try{define(window.location,"protocol",{get:function(){return protocol}})}catch(err){mockedProtocol=protocol}}},{}],181:[function(require,module,exports){var parse=require("querystring").parse;module.exports=ads;var QUERYIDS={btid:"dataxu",urid:"millennial-media"};function ads(query){var params=parse(query);for(var key in params){for(var id in QUERYIDS){if(key===id){return{id:params[key],type:QUERYIDS[id]}}}}}},{querystring:125}],182:[function(require,module,exports){var encode=require("base64-encode");var cors=require("has-cors");var jsonp=require("jsonp");var JSON=require("json");exports=module.exports=cors?json:base64;exports.callback="callback";exports.prefix="data";exports.json=json;exports.base64=base64;exports.type=cors?"xhr":"jsonp";function json(url,obj,headers,fn){if(3==arguments.length)fn=headers,headers={};var req=new XMLHttpRequest;req.onerror=fn;req.onreadystatechange=done;req.open("POST",url,true);for(var k in headers)req.setRequestHeader(k,headers[k]);req.send(JSON.stringify(obj));function done(){if(4==req.readyState)return fn(null,req)}}function base64(url,obj,_,fn){if(3==arguments.length)fn=_;var prefix=exports.prefix;obj=encode(JSON.stringify(obj));obj=encodeURIComponent(obj);url+="?"+prefix+"="+obj;jsonp(url,{param:exports.callback},function(err,obj){if(err)return fn(err);fn(null,{url:url,body:obj})})}},{"base64-encode":186,"has-cors":187,jsonp:188,json:164}],186:[function(require,module,exports){var utf8Encode=require("utf8-encode");var keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";module.exports=encode;function encode(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=utf8Encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=(chr1&3)<<4|chr2>>4;enc3=(chr2&15)<<2|chr3>>6;enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64}else if(isNaN(chr3)){enc4=64}output=output+keyStr.charAt(enc1)+keyStr.charAt(enc2)+keyStr.charAt(enc3)+keyStr.charAt(enc4)}return output}},{"utf8-encode":189}],189:[function(require,module,exports){module.exports=encode;function encode(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c)}else if(c>127&&c<2048){utftext+=String.fromCharCode(c>>6|192);utftext+=String.fromCharCode(c&63|128)}else{utftext+=String.fromCharCode(c>>12|224);utftext+=String.fromCharCode(c>>6&63|128);utftext+=String.fromCharCode(c&63|128)}}return utftext}},{}],187:[function(require,module,exports){try{module.exports=typeof XMLHttpRequest!=="undefined"&&"withCredentials"in new XMLHttpRequest}catch(err){module.exports=false}},{}],188:[function(require,module,exports){var debug=require("debug")("jsonp");module.exports=jsonp;var count=0;function noop(){}function jsonp(url,opts,fn){if("function"==typeof opts){fn=opts;opts={}}if(!opts)opts={};var prefix=opts.prefix||"__jp";var param=opts.param||"callback";var timeout=null!=opts.timeout?opts.timeout:6e4;var enc=encodeURIComponent;var target=document.getElementsByTagName("script")[0]||document.head;var script;var timer;var id=prefix+count++;if(timeout){timer=setTimeout(function(){cleanup();if(fn)fn(new Error("Timeout"))},timeout)}function cleanup(){script.parentNode.removeChild(script);window[id]=noop}window[id]=function(data){debug("jsonp got",data);if(timer)clearTimeout(timer);cleanup();if(fn)fn(null,data)};url+=(~url.indexOf("?")?"&":"?")+param+"="+enc(id);url=url.replace("?&","?");debug('jsonp req "%s"',url);script=document.createElement("script");script.src=url;target.parentNode.insertBefore(script,target)}},{debug:190}],190:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":191,"./debug":192}],191:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt); var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],192:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],183:[function(require,module,exports){var debug=require("debug")("cookie");module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toUTCString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}function encode(value){try{return encodeURIComponent(value)}catch(e){debug("error `encode(%o)` - %o",value,e)}}function decode(value){try{return decodeURIComponent(value)}catch(e){debug("error `decode(%o)` - %o",value,e)}}},{debug:190}],184:[function(require,module,exports){module.exports=function uuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)}},{}],75:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.16/native/raven.min.js">');Sentry.prototype.initialize=function(){var dsn=this.options.config;window.RavenConfig={dsn:dsn};this.load(this.ready)};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":88,is:91}],76:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//www.snapengage.com/cdn/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":88,is:91}],77:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":88,bind:101,when:131}],78:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":88,slug:99,"global-queue":158}],79:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"analytics.js-integration":88,alias:162,clone:95}],80:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").option("page","").tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.page=function(page){if(this.options.page){this.load({pixelId:this.options.page})}};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(pixelId){self.load({pixelId:pixelId})})}},{"analytics.js-integration":88,each:4}],81:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var clone=require("clone");var Userlike=module.exports=integration("Userlike").assumesPageview().global("userlikeConfig").global("userlikeData").option("secretKey","").tag('<script src="//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/{{ secretKey }}.js">');Userlike.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});segment_base_info=clone(this.options);segment_base_info.visitor={name:identify.name(),email:identify.email()};if(!window.userlikeData)window.userlikeData={custom:{}};window.userlikeData.custom.segmentio=segment_base_info;this.load(function(){self.ready()})};Userlike.prototype.loaded=function(){return!!(window.userlikeConfig&&window.userlikeData)}},{"analytics.js-integration":88,facade:132,clone:95}],82:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("screenshotEnabled",true).option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).option("customTicketFields",{}).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position",screenshotEnabled:"screenshot_enabled",customTicketFields:"ticket_custom_fields"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":88,"global-queue":158,"convert-dates":163,"to-unix-timestamp":193,alias:162,clone:95}],193:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],83:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var objCase=require("obj-case");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){var regex=/[uU]nsubscribe/;if(track.event().match(regex)){push("unsubscribe",{id:track.properties().id})}else{push("track",track.event(),track.properties())}};Vero.prototype.alias=function(alias){var to=alias.to();if(alias.from()){push("reidentify",to,alias.from())}else{push("reidentify",to)}}},{"analytics.js-integration":88,"global-queue":158,"component/cookie":183,"obj-case":92}],84:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"analytics.js-integration":88,"next-tick":103,each:4}],85:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":88,"use-https":90}],86:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":88,"to-snake-case":89,"is-email":154,extend:130,each:4,type:113}],87:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).option("clickmap",false).option("webvisor",false).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;var clickmap=this.options.clickmap;var webvisor=this.options.webvisor;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id,clickmap:clickmap,webvisor:webvisor})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":88,"next-tick":103,bind:101,when:131}],3:[function(require,module,exports){var _analytics=window.analytics;var after=require("after");var bind=require("bind");var callback=require("callback");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 pageDefaults=require("./pageDefaults");var pick=require("pick");var prevent=require("prevent");var querystring=require("querystring");var normalize=require("./normalize");var size=require("object").length;var keys=require("object").keys;var memory=require("./memory");var store=require("./store");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;exports.memory=memory;function Analytics(){this._options({});this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;this.log=debug("analytics.js");bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page();self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.log("initialize %o - %o",name,opts);self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.setAnonymousId=function(id){this.user().anonymousId(id);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);var msg=this.normalize({options:options,traits:user.traits(),userId:user.id()});this._invoke("identify",new Identify(msg));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);var msg=this.normalize({options:options,traits:group.traits(),groupId:group.id()});this._invoke("group",new Group(msg));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;var plan=this.options.plan||{};var events=plan.track||{};var msg=this.normalize({properties:properties,options:options,event:event});if(plan=events[event]){this.log("plan %o - %o",event,plan);if(false==plan.enabled)return this._callback(fn);defaults(msg.integrations,plan.integrations||{})}this._invoke("track",new Track(msg));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;var href=el.getAttribute("href")||el.getAttributeNS("http://www.w3.org/1999/xlink","href")||el.getAttribute("xlink:href");self.track(ev,props);if(href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;properties=clone(properties)||{};if(name)properties.name=name;if(category)properties.category=category;var defs=pageDefaults();defaults(properties,defs);var overrides=pick(keys(defs),properties);if(!is.empty(overrides)){options=options||{};options.context=options.context||{};options.context.page=overrides}var msg=this.normalize({properties:properties,category:category,options:options,name:name});this._invoke("page",new Page(msg));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;var msg=this.normalize({options:options,previousId:from,userId:to});this._invoke("alias",new Alias(msg));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};this.options=options;cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype.reset=function(){this.user().logout();this.group().logout()};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);if(q.ajs_aid)user.anonymousId(q.ajs_aid);return this};Analytics.prototype.normalize=function(msg){msg=normalize(msg,keys(this._integrations));if(msg.anonymousId)user.anonymousId(msg.anonymousId);msg.anonymousId=user.anonymousId();msg.context.page=defaults(msg.context.page||{},pageDefaults());return msg};Analytics.prototype.noConflict=function(){window.analytics=_analytics;return this}},{after:111,bind:194,callback:94,clone:95,"./cookie":195,debug:190,defaults:97,each:4,emitter:110,"./group":196,is:91,"is-email":154,"is-meta":197,"new-date":146,event:198,"./pageDefaults":199,pick:200,prevent:201,querystring:202,"./normalize":203,object:170,"./memory":204,"./store":205,"./user":206,facade:132}],194:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:101,"bind-all":102}],195:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:190,bind:194,cookie:183,clone:95,defaults:97,json:164,"top-domain":124}],196:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{debug:190,"./entity":207,inherit:208,bind:194}],207:[function(require,module,exports){var debug=require("debug")("analytics:entity");var traverse=require("isodate-traverse");var defaults=require("defaults");var memory=require("./memory");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options);this.initialize()}Entity.prototype.initialize=function(){cookie.set("ajs:cookies",true);if(cookie.get("ajs:cookies")){cookie.remove("ajs:cookies");this._storage=cookie;return}if(store.enabled){this._storage=store;return}debug("warning using memory store both cookies and localStorage are disabled");this._storage=memory};Entity.prototype.storage=function(){return this._storage};Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var ret=this._options.persist?this.storage().get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){this.storage().set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits; return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{debug:190,"isodate-traverse":142,defaults:97,"./memory":204,"./cookie":195,"./store":205,extend:130,clone:95}],204:[function(require,module,exports){var clone=require("clone");var bind=require("bind");var has=Object.prototype.hasOwnProperty;module.exports=bind.all(new Memory);function Memory(){this.store={}}Memory.prototype.set=function(key,value){this.store[key]=clone(value);return true};Memory.prototype.get=function(key){if(!has.call(this.store,key))return;return clone(this.store[key])};Memory.prototype.remove=function(key){delete this.store[key];return true}},{clone:95,bind:194}],205:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:194,defaults:97,"store.js":209}],209:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:164}],208:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],197:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],198:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],199:[function(require,module,exports){var canonical=require("canonical");var url=require("url");function pageDefaults(){return{path:canonicalPath(),referrer:document.referrer,search:location.search,title:document.title,url:canonicalUrl(location.search)}}function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1===i?url:url.slice(0,i)}module.exports=pageDefaults},{canonical:171,url:173}],200:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString;var existy=function(val){return val!=null};var isArray=function(val){return objToString.call(val)==="[object Array]"};var isString=function(val){return typeof val==="string"||objToString.call(val)==="[object String]"};var isObject=function(val){return val!=null&&typeof val==="object"};var pick=function pick(props,object){if(!existy(object)||!isObject(object)){return{}}if(isString(props)){props=[props]}if(!isArray(props)){props=[]}var result={};for(var i=0;i<props.length;i+=1){if(isString(props[i])&&props[i]in object){result[props[i]]=object[props[i]]}}return result};module.exports=pick},{}],201:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],202:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:126,type:7}],203:[function(require,module,exports){var debug=require("debug")("analytics.js:normalize");var indexof=require("component/indexof");var defaults=require("defaults");var map=require("component/map");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;module.exports=normalize;var toplevel=["integrations","anonymousId","timestamp","context"];function normalize(msg,list){var lower=map(list,function(s){return s.toLowerCase()});var opts=msg.options||{};var integrations=opts.integrations||{};var providers=opts.providers||{};var context=opts.context||{};var ret={};debug("<-",msg);each(opts,function(key,value){if(!integration(key))return;if(!has.call(integrations,key))integrations[key]=value;delete opts[key]});delete opts.providers;each(providers,function(key,value){if(!integration(key))return;if(is.object(integrations[key]))return;if(has.call(integrations,key)&&"boolean"==typeof providers[key])return;integrations[key]=value});each(opts,function(key){if(~indexof(toplevel,key)){ret[key]=opts[key]}else{context[key]=opts[key]}});delete msg.options;ret.integrations=integrations;ret.context=context;ret=defaults(ret,msg);debug("->",ret);return ret;function integration(name){return!!(~indexof(list,name)||"all"==name.toLowerCase()||~indexof(lower,name.toLowerCase()))}}},{debug:190,"component/indexof":116,defaults:97,"component/map":210,each:4,is:91}],210:[function(require,module,exports){var toFunction=require("to-function");module.exports=function(arr,fn){var ret=[];fn=toFunction(fn);for(var i=0;i<arr.length;++i){ret.push(fn(arr[i],i))}return ret}},{"to-function":174}],206:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");var uuid=require("uuid");var rawCookie=require("cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.id=function(id){var prev=this._getId();var ret=Entity.prototype.id.apply(this,arguments);if(null==prev)return ret;if(prev!=id&&id)this.anonymousId(null);return ret};User.prototype.anonymousId=function(anonId){var store=this.storage();if(arguments.length){store.set("ajs_anonymous_id",anonId);return this}if(anonId=store.get("ajs_anonymous_id")){return anonId}if(anonId=rawCookie("_sio")){anonId=anonId.split("----")[0];store.set("ajs_anonymous_id",anonId);store.remove("_sio");return anonId}anonId=uuid();store.set("ajs_anonymous_id",anonId);return store.get("ajs_anonymous_id")};User.prototype.logout=function(){Entity.prototype.logout.call(this);this.anonymousId(null)};User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{debug:190,"./entity":207,inherit:208,bind:194,"./cookie":195,uuid:184,cookie:183}],5:[function(require,module,exports){module.exports={name:"analytics",version:"2.8.5",main:"analytics.js",dependencies:{},devDependencies:{}}},{}]},{},{1:""}));
src/layout/hero-head.js
bokuweb/re-bulma
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from '../../build/styles'; import { getCallbacks } from '../helper/helper'; export default class HeroHead extends Component { static propTypes = { style: PropTypes.object, children: PropTypes.any, className: PropTypes.string, }; static defaultProps = { style: {}, className: '', }; createClassName() { return [ styles.heroHead, this.props.className, ].join(' ').trim(); } render() { return ( <section {...getCallbacks(this.props)} style={this.props.style} className={this.createClassName()} > {this.props.children} </section> ); } }
node_modules/react-router/es6/RouterContext.js
sharonjean/React-Netflix
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import invariant from 'invariant'; import React from 'react'; import deprecateObjectProperties from './deprecateObjectProperties'; import getRouteParams from './getRouteParams'; import { isReactChildren } from './RouteUtils'; import warning from './routerWarning'; var _React$PropTypes = React.PropTypes; var array = _React$PropTypes.array; var func = _React$PropTypes.func; var object = _React$PropTypes.object; /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = React.createClass({ displayName: 'RouterContext', propTypes: { history: object, router: object.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired, createElement: func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: React.createElement }; }, childContextTypes: { history: object, location: object.isRequired, router: object.isRequired }, getChildContext: function getChildContext() { var _props = this.props; var router = _props.router; var history = _props.history; var location = _props.location; if (!router) { process.env.NODE_ENV !== 'production' ? warning(false, '`<RouterContext>` expects a `router` rather than a `history`') : void 0; router = _extends({}, history, { setRouteLeaveHook: history.listenBeforeLeavingRoute }); delete router.listenBeforeLeavingRoute; } if (process.env.NODE_ENV !== 'production') { location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. http://tiny.cc/router-accessinglocation'); } return { history: history, location: location, router: router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props2 = this.props; var history = _props2.history; var location = _props2.location; var routes = _props2.routes; var params = _props2.params; var components = _props2.components; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = getRouteParams(route, params); var props = { history: history, location: location, params: params, route: route, routeParams: routeParams, routes: routes }; if (isReactChildren(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0; return element; } }); export default RouterContext;
app/src/components/content/UserPage/index.js
ouxu/NEUQ-OJ
/** * Created by out_xu on 16/12/30. */ import React from 'react' import QueueAnim from 'rc-queue-anim' import { Icon, Tooltip } from 'antd' import { Link } from 'react-router' import './index.less' import DashCard from './DashCard' import StatusCard from './StatusCard' import GroupStatus from './GroupStatus' class UserPanel extends React.Component { render () { const {user, status} = this.props return ( <QueueAnim className='userpage-wrap' delay={100}> <div className='userpage-header' key='userpage-1'> <span className='userpage-header-title'> <Icon type='user' /> <span> {user.name} / 个人资料</span> </span> <div className='userpage-header-other'> <Tooltip placement='left' title={user.email ? user.email : ''}> <Icon type='mail' /> </Tooltip> <Tooltip placement='left' title={user.mobile ? user.mobile : ''}> <Icon type='mobile' /> </Tooltip> <Tooltip placement='left' title={user.school ? user.school : ''}> <Icon type='flag' /> </Tooltip> <Tooltip placement='left' title='编辑个人信息'> <Link to='/userpage/edit'> <Icon type='edit' /> </Link> </Tooltip> </div> </div> <DashCard status={status} /> <StatusCard userdata={user} /> <GroupStatus /> </QueueAnim> ) } } export default UserPanel
ajax/libs/vue/0.12.0/vue.js
bspaulding/cdnjs
/** * Vue.js v0.12.0 * (c) 2015 Evan You * Released under the MIT License. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["Vue"] = factory(); else root["Vue"] = 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 _ = __webpack_require__(1) var extend = _.extend /** * The exposed Vue constructor. * * API conventions: * - public API methods/properties are prefiexed with `$` * - internal methods/properties are prefixed with `_` * - non-prefixed properties are assumed to be proxied user * data. * * @constructor * @param {Object} [options] * @public */ function Vue (options) { this._init(options) } /** * Mixin global API */ extend(Vue, __webpack_require__(9)) /** * Vue and every constructor that extends Vue has an * associated options object, which can be accessed during * compilation steps as `this.constructor.options`. * * These can be seen as the default options of every * Vue instance. */ Vue.options = { directives: __webpack_require__(27), filters: __webpack_require__(49), transitions: {}, components: {}, elementDirectives: { content: __webpack_require__(51) } } /** * Build up the prototype */ var p = Vue.prototype /** * $data has a setter which does a bunch of * teardown/setup work */ Object.defineProperty(p, '$data', { get: function () { return this._data }, set: function (newData) { if (newData !== this._data) { this._setData(newData) } } }) /** * Mixin internal instance methods */ extend(p, __webpack_require__(52)) extend(p, __webpack_require__(53)) extend(p, __webpack_require__(54)) extend(p, __webpack_require__(55)) extend(p, __webpack_require__(57)) /** * Mixin public API methods */ extend(p, __webpack_require__(58)) extend(p, __webpack_require__(59)) extend(p, __webpack_require__(60)) extend(p, __webpack_require__(61)) extend(p, __webpack_require__(62)) module.exports = _.Vue = Vue /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var lang = __webpack_require__(4) var extend = lang.extend extend(exports, lang) extend(exports, __webpack_require__(5)) extend(exports, __webpack_require__(6)) extend(exports, __webpack_require__(2)) extend(exports, __webpack_require__(7)) extend(exports, __webpack_require__(8)) /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(3) var commonTagRE = /^(div|p|span|img|a|br|ul|ol|li|h1|h2|h3|h4|h5|code|pre)$/ var tableElementsRE = /^caption|colgroup|thead|tfoot|tbody|tr|td|th$/ /** * Check if an element is a component, if yes return its * component id. * * @param {Element} el * @param {Object} options * @return {String|undefined} */ exports.checkComponent = function (el, options) { var tag = el.tagName.toLowerCase() if (tag === 'component') { // dynamic syntax var exp = el.getAttribute('is') el.removeAttribute('is') return exp } else if ( !commonTagRE.test(tag) && _.resolveAsset(options, 'components', tag) ) { return tag } else if ( tableElementsRE.test(tag) && (tag = _.attr(el, 'component')) ) { return tag } } /** * Create an "anchor" for performing dom insertion/removals. * This is used in a number of scenarios: * - block instance * - v-html * - v-if * - component * - repeat * * @param {String} content * @param {Boolean} persist - IE trashes empty textNodes on * cloneNode(true), so in certain * cases the anchor needs to be * non-empty to be persisted in * templates. * @return {Comment|Text} */ exports.createAnchor = function (content, persist) { return config.debug ? document.createComment(content) : document.createTextNode(persist ? ' ' : '') } /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { module.exports = { /** * The prefix to look for when parsing directives. * * @type {String} */ prefix: 'v-', /** * Whether to print debug messages. * Also enables stack trace for warnings. * * @type {Boolean} */ debug: false, /** * Whether to suppress warnings. * * @type {Boolean} */ silent: false, /** * Whether allow observer to alter data objects' * __proto__. * * @type {Boolean} */ proto: true, /** * Whether to parse mustache tags in templates. * * @type {Boolean} */ interpolate: true, /** * Whether to use async rendering. */ async: true, /** * Whether to warn against errors caught when evaluating * expressions. */ warnExpressionErrors: true, /** * Internal flag to indicate the delimiters have been * changed. * * @type {Boolean} */ _delimitersChanged: true, /** * List of asset types that a component can own. * * @type {Array} */ _assetTypes: [ 'directive', 'elementDirective', 'filter', 'transition' ] } /** * Interpolation delimiters. * We need to mark the changed flag so that the text parser * knows it needs to recompile the regex. * * @type {Array<String>} */ var delimiters = ['{{', '}}'] Object.defineProperty(module.exports, 'delimiters', { get: function () { return delimiters }, set: function (val) { delimiters = val this._delimitersChanged = true } }) /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /** * Check is a string starts with $ or _ * * @param {String} str * @return {Boolean} */ exports.isReserved = function (str) { var c = (str + '').charCodeAt(0) return c === 0x24 || c === 0x5F } /** * Guard text output, make sure undefined outputs * empty string * * @param {*} value * @return {String} */ exports.toString = function (value) { return value == null ? '' : value.toString() } /** * Check and convert possible numeric numbers before * setting back to data * * @param {*} value * @return {*|Number} */ exports.toNumber = function (value) { return ( isNaN(value) || value === null || typeof value === 'boolean' ) ? value : Number(value) } /** * Strip quotes from a string * * @param {String} str * @return {String | false} */ exports.stripQuotes = function (str) { var a = str.charCodeAt(0) var b = str.charCodeAt(str.length - 1) return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : false } /** * Replace helper * * @param {String} _ - matched delimiter * @param {String} c - matched char * @return {String} */ function toUpper (_, c) { return c ? c.toUpperCase () : '' } /** * Camelize a hyphen-delmited string. * * @param {String} str * @return {String} */ var camelRE = /-(\w)/g exports.camelize = function (str) { return str.replace(camelRE, toUpper) } /** * Converts hyphen/underscore/slash delimitered names into * camelized classNames. * * e.g. my-component => MyComponent * some_else => SomeElse * some/comp => SomeComp * * @param {String} str * @return {String} */ var classifyRE = /(?:^|[-_\/])(\w)/g exports.classify = function (str) { return str.replace(classifyRE, toUpper) } /** * Simple bind, faster than native * * @param {Function} fn * @param {Object} ctx * @return {Function} */ exports.bind = function (fn, ctx) { return function (a) { var l = arguments.length return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } } /** * Convert an Array-like object to a real Array. * * @param {Array-like} list * @param {Number} [start] - start index * @return {Array} */ exports.toArray = function (list, start) { start = start || 0 var i = list.length - start var ret = new Array(i) while (i--) { ret[i] = list[i + start] } return ret } /** * Mix properties into target object. * * @param {Object} to * @param {Object} from */ exports.extend = function (to, from) { for (var key in from) { to[key] = from[key] } return to } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. * * @param {*} obj * @return {Boolean} */ exports.isObject = function (obj) { return obj && typeof obj === 'object' } /** * Strict object type check. Only returns true * for plain JavaScript objects. * * @param {*} obj * @return {Boolean} */ var toString = Object.prototype.toString exports.isPlainObject = function (obj) { return toString.call(obj) === '[object Object]' } /** * Array type check. * * @param {*} obj * @return {Boolean} */ exports.isArray = function (obj) { return Array.isArray(obj) } /** * Define a non-enumerable property * * @param {Object} obj * @param {String} key * @param {*} val * @param {Boolean} [enumerable] */ exports.define = function (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value : val, enumerable : !!enumerable, writable : true, configurable : true }) } /** * Debounce a function so it only gets called after the * input stops arriving after the given wait period. * * @param {Function} func * @param {Number} wait * @return {Function} - the debounced function */ exports.debounce = function(func, wait) { var timeout, args, context, timestamp, result var later = function() { var last = Date.now() - timestamp if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last) } else { timeout = null result = func.apply(context, args) if (!timeout) context = args = null } } return function() { context = this args = arguments timestamp = Date.now() if (!timeout) { timeout = setTimeout(later, wait) } return result } } /** * Manual indexOf because it's slightly faster than * native. * * @param {Array} arr * @param {*} obj */ exports.indexOf = function (arr, obj) { for (var i = 0, l = arr.length; i < l; i++) { if (arr[i] === obj) return i } return -1 } /** * Make a cancellable version of an async callback. * * @param {Function} fn * @return {Function} */ exports.cancellable = function (fn) { var cb = function () { if (!cb.cancelled) { return fn.apply(this, arguments) } } cb.cancel = function () { cb.cancelled = true } return cb } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { // can we use __proto__? exports.hasProto = '__proto__' in {} // Browser environment sniffing var inBrowser = exports.inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]' exports.isIE9 = inBrowser && navigator.userAgent.toLowerCase().indexOf('msie 9.0') > 0 exports.isAndroid = inBrowser && navigator.userAgent.toLowerCase().indexOf('android') > 0 // Transition property/event sniffing if (inBrowser && !exports.isIE9) { var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined exports.transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition' exports.transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend' exports.animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation' exports.animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend' } /** * Defer a task to execute it asynchronously. Ideally this * should be executed as a microtask, so we leverage * MutationObserver if it's available, and fallback to * setTimeout(0). * * @param {Function} cb * @param {Object} ctx */ exports.nextTick = (function () { var callbacks = [] var pending = false var timerFunc function handle () { pending = false var copies = callbacks.slice(0) callbacks = [] for (var i = 0; i < copies.length; i++) { copies[i]() } } /* istanbul ignore if */ if (typeof MutationObserver !== 'undefined') { var counter = 1 var observer = new MutationObserver(handle) var textNode = document.createTextNode(counter) observer.observe(textNode, { characterData: true }) timerFunc = function () { counter = (counter + 1) % 2 textNode.data = counter } } else { timerFunc = setTimeout } return function (cb, ctx) { var func = ctx ? function () { cb.call(ctx) } : cb callbacks.push(func) if (pending) return pending = true timerFunc(handle, 0) } })() /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var config = __webpack_require__(3) /** * Check if a node is in the document. * Note: document.documentElement.contains should work here * but always returns false for comment nodes in phantomjs, * making unit tests difficult. This is fixed byy doing the * contains() check on the node's parentNode instead of * the node itself. * * @param {Node} node * @return {Boolean} */ exports.inDoc = function (node) { var doc = document.documentElement var parent = node && node.parentNode return doc === node || doc === parent || !!(parent && parent.nodeType === 1 && (doc.contains(parent))) } /** * Extract an attribute from a node. * * @param {Node} node * @param {String} attr */ exports.attr = function (node, attr) { attr = config.prefix + attr var val = node.getAttribute(attr) if (val !== null) { node.removeAttribute(attr) } return val } /** * Insert el before target * * @param {Element} el * @param {Element} target */ exports.before = function (el, target) { target.parentNode.insertBefore(el, target) } /** * Insert el after target * * @param {Element} el * @param {Element} target */ exports.after = function (el, target) { if (target.nextSibling) { exports.before(el, target.nextSibling) } else { target.parentNode.appendChild(el) } } /** * Remove el from DOM * * @param {Element} el */ exports.remove = function (el) { el.parentNode.removeChild(el) } /** * Prepend el to target * * @param {Element} el * @param {Element} target */ exports.prepend = function (el, target) { if (target.firstChild) { exports.before(el, target.firstChild) } else { target.appendChild(el) } } /** * Replace target with el * * @param {Element} target * @param {Element} el */ exports.replace = function (target, el) { var parent = target.parentNode if (parent) { parent.replaceChild(el, target) } } /** * Add event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ exports.on = function (el, event, cb) { el.addEventListener(event, cb) } /** * Remove event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ exports.off = function (el, event, cb) { el.removeEventListener(event, cb) } /** * Add class with compatibility for IE & SVG * * @param {Element} el * @param {Strong} cls */ exports.addClass = function (el, cls) { if (el.classList) { el.classList.add(cls) } else { var cur = ' ' + (el.getAttribute('class') || '') + ' ' if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()) } } } /** * Remove class with compatibility for IE & SVG * * @param {Element} el * @param {Strong} cls */ exports.removeClass = function (el, cls) { if (el.classList) { el.classList.remove(cls) } else { var cur = ' ' + (el.getAttribute('class') || '') + ' ' var tar = ' ' + cls + ' ' while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' ') } el.setAttribute('class', cur.trim()) } } /** * Extract raw content inside an element into a temporary * container div * * @param {Element} el * @param {Boolean} asFragment * @return {Element} */ exports.extractContent = function (el, asFragment) { var child var rawContent /* istanbul ignore if */ if ( exports.isTemplate(el) && el.content instanceof DocumentFragment ) { el = el.content } if (el.hasChildNodes()) { rawContent = asFragment ? document.createDocumentFragment() : document.createElement('div') /* jshint boss:true */ while (child = el.firstChild) { rawContent.appendChild(child) } } return rawContent } /** * Check if an element is a template tag. * Note if the template appears inside an SVG its tagName * will be in lowercase. * * @param {Element} el */ exports.isTemplate = function (el) { return el.tagName && el.tagName.toLowerCase() === 'template' } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var config = __webpack_require__(3) /** * Enable debug utilities. The enableDebug() function and * all _.log() & _.warn() calls will be dropped in the * minified production build. */ enableDebug() function enableDebug () { var hasConsole = typeof console !== 'undefined' /** * Log a message. * * @param {String} msg */ exports.log = function (msg) { if (hasConsole && config.debug) { console.log('[Vue info]: ' + msg) } } /** * We've got a problem here. * * @param {String} msg */ exports.warn = function (msg, e) { if (hasConsole && (!config.silent || config.debug)) { console.warn('[Vue warn]: ' + msg) /* istanbul ignore if */ if (config.debug) { /* jshint debug: true */ console.warn((e || new Error('Warning Stack Trace')).stack) } } } /** * Assert asset exists */ exports.assertAsset = function (val, type, id) { /* istanbul ignore if */ if (type === 'directive') { if (id === 'component') { exports.warn( 'v-component can only be used on table elements ' + 'in ^0.12.0. Use custom element syntax instead.' ) return } if (id === 'with') { exports.warn( 'v-with has been deprecated in ^0.12.0. ' + 'Use props instead.' ) return } if (id === 'events') { exports.warn( 'v-events has been deprecated in ^0.12.0. ' + 'Pass down methods as callback props instead.' ) return } } if (!val) { exports.warn('Failed to resolve ' + type + ': ' + id) } } } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var extend = _.extend /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. * * All strategy functions follow the same signature: * * @param {*} parentVal * @param {*} childVal * @param {Vue} [vm] */ var strats = Object.create(null) /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { var key, toVal, fromVal for (key in from) { toVal = to[key] fromVal = from[key] if (!to.hasOwnProperty(key)) { to.$add(key, fromVal) } else if (_.isObject(toVal) && _.isObject(fromVal)) { mergeData(toVal, fromVal) } } return to } /** * Data */ strats.data = function (parentVal, childVal, vm) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (typeof childVal !== 'function') { _.warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.' ) return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( childVal.call(this), parentVal.call(this) ) } } else { // instance merge, return raw object var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } /** * El */ strats.el = function (parentVal, childVal, vm) { if (!vm && childVal && typeof childVal !== 'function') { _.warn( 'The "el" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.' ) return } var ret = childVal || parentVal // invoke the element factory if this is instance merge return vm && typeof ret === 'function' ? ret.call(vm) : ret } /** * Hooks and param attributes are merged as arrays. */ strats.created = strats.ready = strats.attached = strats.detached = strats.beforeCompile = strats.compiled = strats.beforeDestroy = strats.destroyed = strats.props = function (parentVal, childVal) { return childVal ? parentVal ? parentVal.concat(childVal) : _.isArray(childVal) ? childVal : [childVal] : parentVal } /** * 0.11 deprecation warning */ strats.paramAttributes = function () { /* istanbul ignore next */ _.warn( '"paramAttributes" option has been deprecated in 0.12. ' + 'Use "props" instead.' ) } /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ strats.directives = strats.filters = strats.transitions = strats.components = strats.elementDirectives = function (parentVal, childVal) { var res = Object.create(parentVal) return childVal ? extend(res, childVal) : res } /** * Events & Watchers. * * Events & watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = strats.events = function (parentVal, childVal) { if (!childVal) return parentVal if (!parentVal) return childVal var ret = {} extend(ret, parentVal) for (var key in childVal) { var parent = ret[key] var child = childVal[key] if (parent && !_.isArray(parent)) { parent = [parent] } ret[key] = parent ? parent.concat(child) : [child] } return ret } /** * Other object hashes. */ strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) return parentVal if (!parentVal) return childVal var ret = Object.create(parentVal) extend(ret, childVal) return ret } /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal } /** * Make sure component options get converted to actual * constructors. * * @param {Object} components */ function guardComponents (components) { if (components) { var def for (var key in components) { def = components[key] if (_.isPlainObject(def)) { def.name = key components[key] = _.Vue.extend(def) } } } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. * * @param {Object} parent * @param {Object} child * @param {Vue} [vm] - if vm is present, indicates this is * an instantiation merge. */ exports.mergeOptions = function merge (parent, child, vm) { guardComponents(child.components) var options = {} var key if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = merge(parent, child.mixins[i], vm) } } for (key in parent) { mergeField(key) } for (key in child) { if (!(parent.hasOwnProperty(key))) { mergeField(key) } } function mergeField (key) { var strat = strats[key] || defaultStrat options[key] = strat(parent[key], child[key], vm, key) } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. * * @param {Object} options * @param {String} type * @param {String} id * @return {Object|Function} */ exports.resolveAsset = function resolve (options, type, id) { var asset = options[type][id] while (!asset && options._parent) { options = options._parent.$options asset = options[type][id] } return asset } /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(3) /** * Expose useful internals */ exports.util = _ exports.nextTick = _.nextTick exports.config = __webpack_require__(3) exports.compiler = __webpack_require__(10) exports.parsers = { path: __webpack_require__(23), text: __webpack_require__(14), template: __webpack_require__(12), directive: __webpack_require__(15), expression: __webpack_require__(22) } /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ exports.cid = 0 var cid = 1 /** * Class inehritance * * @param {Object} extendOptions */ exports.extend = function (extendOptions) { extendOptions = extendOptions || {} var Super = this var Sub = createClass( extendOptions.name || Super.options.name || 'VueComponent' ) Sub.prototype = Object.create(Super.prototype) Sub.prototype.constructor = Sub Sub.cid = cid++ Sub.options = _.mergeOptions( Super.options, extendOptions ) Sub['super'] = Super // allow further extension Sub.extend = Super.extend // create asset registers, so extended classes // can have their private assets too. createAssetRegisters(Sub) return Sub } /** * A function that returns a sub-class constructor with the * given name. This gives us much nicer output when * logging instances in the console. * * @param {String} name * @return {Function} */ function createClass (name) { return new Function( 'return function ' + _.classify(name) + ' (options) { this._init(options) }' )() } /** * Plugin system * * @param {Object} plugin */ exports.use = function (plugin) { // additional parameters var args = _.toArray(arguments, 1) args.unshift(this) if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args) } else { plugin.apply(null, args) } return this } /** * Define asset registration methods on a constructor. * * @param {Function} Constructor */ function createAssetRegisters (Constructor) { /* Asset registration methods share the same signature: * * @param {String} id * @param {*} definition */ config._assetTypes.forEach(function (type) { Constructor[type] = function (id, definition) { if (!definition) { return this.options[type + 's'][id] } else { this.options[type + 's'][id] = definition } } }) /** * Component registration needs to automatically invoke * Vue.extend on object values. * * @param {String} id * @param {Object|Function} definition */ Constructor.component = function (id, definition) { if (!definition) { return this.options.components[id] } else { if (_.isPlainObject(definition)) { definition.name = id definition = _.Vue.extend(definition) } this.options.components[id] = definition } } } createAssetRegisters(exports) /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) _.extend(exports, __webpack_require__(11)) _.extend(exports, __webpack_require__(26)) /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(3) var textParser = __webpack_require__(14) var dirParser = __webpack_require__(15) var templateParser = __webpack_require__(12) var resolveAsset = _.resolveAsset // internal directives var propDef = __webpack_require__(16) var componentDef = __webpack_require__(25) // terminal directives var terminalDirectives = [ 'repeat', 'if' ] /** * Compile a template and return a reusable composite link * function, which recursively contains more link functions * inside. This top level compile function would normally * be called on instance root nodes, but can also be used * for partial compilation if the partial argument is true. * * The returned composite link function, when called, will * return an unlink function that tearsdown all directives * created during the linking phase. * * @param {Element|DocumentFragment} el * @param {Object} options * @param {Boolean} partial * @param {Vue} [host] - host vm of transcluded content * @return {Function} */ exports.compile = function (el, options, partial, host) { // link function for the node itself. var nodeLinkFn = partial || !options._asComponent ? compileNode(el, options) : null // link function for the childNodes var childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && el.tagName !== 'SCRIPT' && el.hasChildNodes() ? compileNodeList(el.childNodes, options) : null /** * A composite linker function to be called on a already * compiled piece of DOM, which instantiates all directive * instances. * * @param {Vue} vm * @param {Element|DocumentFragment} el * @return {Function|undefined} */ return function compositeLinkFn (vm, el) { // cache childNodes before linking parent, fix #657 var childNodes = _.toArray(el.childNodes) // link var dirs = linkAndCapture(function () { if (nodeLinkFn) nodeLinkFn(vm, el, host) if (childLinkFn) childLinkFn(vm, childNodes, host) }, vm) /** * The linker function returns an unlink function that * tearsdown all directives instances generated during * the process. * * @param {Boolean} destroying */ return function unlink (destroying) { teardownDirs(vm, dirs, destroying) } } } /** * Apply a linker to a vm/element pair and capture the * directives created during the process. * * @param {Function} linker * @param {Vue} vm */ function linkAndCapture (linker, vm) { var originalDirCount = vm._directives.length linker() return vm._directives.slice(originalDirCount) } /** * Teardown partial linked directives. * * @param {Vue} vm * @param {Array} dirs * @param {Boolean} destroying */ function teardownDirs (vm, dirs, destroying) { if (!dirs) return var i = dirs.length while (i--) { dirs[i]._teardown() if (!destroying) { vm._directives.$remove(dirs[i]) } } } /** * Compile the root element of an instance. There are * 3 types of things to process here: * * 1. props on parent container (child scope) * 2. other attrs on parent container (parent scope) * 3. attrs on the component template root node, if * replace:true (child scope) * * Also, if this is a block instance, we only need to * compile 1 & 2 here. * * This function does compile and link at the same time, * since root linkers can not be reused. It returns the * unlink function for potential parent directives on the * container. * * @param {Vue} vm * @param {Element} el * @param {Object} options * @return {Function} */ exports.compileAndLinkRoot = function (vm, el, options) { var containerAttrs = options._containerAttrs var replacerAttrs = options._replacerAttrs var props = options.props var propsLinkFn, parentLinkFn, replacerLinkFn // 1. props propsLinkFn = props && containerAttrs ? compileProps(el, containerAttrs, props) : null // only need to compile other attributes for // non-block instances if (el.nodeType !== 11) { // for components, container and replacer need to be // compiled separately and linked in different scopes. if (options._asComponent) { // 2. container attributes if (containerAttrs) { parentLinkFn = compileDirectives(containerAttrs, options) } if (replacerAttrs) { // 3. replacer attributes replacerLinkFn = compileDirectives(replacerAttrs, options) } } else { // non-component, just compile as a normal element. replacerLinkFn = compileDirectives(el, options) } } // link parent dirs var parent = vm.$parent var parentDirs if (parent && parentLinkFn) { parentDirs = linkAndCapture(function () { parentLinkFn(parent, el) }, parent) } // link self var selfDirs = linkAndCapture(function () { if (propsLinkFn) propsLinkFn(vm, null) if (replacerLinkFn) replacerLinkFn(vm, el) }, vm) // return the unlink function that tearsdown parent // container directives. return function rootUnlinkFn () { teardownDirs(parent, parentDirs) teardownDirs(vm, selfDirs) } } /** * Compile a node and return a nodeLinkFn based on the * node type. * * @param {Node} node * @param {Object} options * @return {Function|null} */ function compileNode (node, options) { var type = node.nodeType if (type === 1 && node.tagName !== 'SCRIPT') { return compileElement(node, options) } else if (type === 3 && config.interpolate && node.data.trim()) { return compileTextNode(node, options) } else { return null } } /** * Compile an element and return a nodeLinkFn. * * @param {Element} el * @param {Object} options * @return {Function|null} */ function compileElement (el, options) { var hasAttrs = el.hasAttributes() // check element directives var linkFn = checkElementDirectives(el, options) // check terminal directives (repeat & if) if (!linkFn && hasAttrs) { linkFn = checkTerminalDirectives(el, options) } // check component if (!linkFn) { linkFn = checkComponent(el, options) } // normal directives if (!linkFn && hasAttrs) { linkFn = compileDirectives(el, options) } // if the element is a textarea, we need to interpolate // its content on initial render. if (el.tagName === 'TEXTAREA') { var realLinkFn = linkFn linkFn = function (vm, el) { el.value = vm.$interpolate(el.value) if (realLinkFn) realLinkFn(vm, el) } linkFn.terminal = true } return linkFn } /** * Compile a textNode and return a nodeLinkFn. * * @param {TextNode} node * @param {Object} options * @return {Function|null} textNodeLinkFn */ function compileTextNode (node, options) { var tokens = textParser.parse(node.data) if (!tokens) { return null } var frag = document.createDocumentFragment() var el, token for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i] el = token.tag ? processTextToken(token, options) : document.createTextNode(token.value) frag.appendChild(el) } return makeTextNodeLinkFn(tokens, frag, options) } /** * Process a single text token. * * @param {Object} token * @param {Object} options * @return {Node} */ function processTextToken (token, options) { var el if (token.oneTime) { el = document.createTextNode(token.value) } else { if (token.html) { el = document.createComment('v-html') setTokenType('html') } else { // IE will clean up empty textNodes during // frag.cloneNode(true), so we have to give it // something here... el = document.createTextNode(' ') setTokenType('text') } } function setTokenType (type) { token.type = type token.def = resolveAsset(options, 'directives', type) token.descriptor = dirParser.parse(token.value)[0] } return el } /** * Build a function that processes a textNode. * * @param {Array<Object>} tokens * @param {DocumentFragment} frag */ function makeTextNodeLinkFn (tokens, frag) { return function textNodeLinkFn (vm, el) { var fragClone = frag.cloneNode(true) var childNodes = _.toArray(fragClone.childNodes) var token, value, node for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i] value = token.value if (token.tag) { node = childNodes[i] if (token.oneTime) { value = vm.$eval(value) if (token.html) { _.replace(node, templateParser.parse(value, true)) } else { node.data = value } } else { vm._bindDir(token.type, node, token.descriptor, token.def) } } } _.replace(el, fragClone) } } /** * Compile a node list and return a childLinkFn. * * @param {NodeList} nodeList * @param {Object} options * @return {Function|undefined} */ function compileNodeList (nodeList, options) { var linkFns = [] var nodeLinkFn, childLinkFn, node for (var i = 0, l = nodeList.length; i < l; i++) { node = nodeList[i] nodeLinkFn = compileNode(node, options) childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && node.tagName !== 'SCRIPT' && node.hasChildNodes() ? compileNodeList(node.childNodes, options) : null linkFns.push(nodeLinkFn, childLinkFn) } return linkFns.length ? makeChildLinkFn(linkFns) : null } /** * Make a child link function for a node's childNodes. * * @param {Array<Function>} linkFns * @return {Function} childLinkFn */ function makeChildLinkFn (linkFns) { return function childLinkFn (vm, nodes, host) { var node, nodeLinkFn, childrenLinkFn for (var i = 0, n = 0, l = linkFns.length; i < l; n++) { node = nodes[n] nodeLinkFn = linkFns[i++] childrenLinkFn = linkFns[i++] // cache childNodes before linking parent, fix #657 var childNodes = _.toArray(node.childNodes) if (nodeLinkFn) { nodeLinkFn(vm, node, host) } if (childrenLinkFn) { childrenLinkFn(vm, childNodes, host) } } } } /** * Compile param attributes on a root element and return * a props link function. * * @param {Element|DocumentFragment} el * @param {Object} attrs * @param {Array} propNames * @return {Function} propsLinkFn */ var dataAttrRE = /^data-/ var settablePathRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\[[^\[\]]+\])*$/ var literalValueRE = /^(true|false|\d+)$/ var identRE = __webpack_require__(23).identRE function compileProps (el, attrs, propNames) { var props = [] var i = propNames.length var name, value, path, prop, settable, literal, single while (i--) { name = propNames[i] // props could contain dashes, which will be // interpreted as minus calculations by the parser // so we need to camelize the path here path = _.camelize(name.replace(dataAttrRE, '')) if (/[A-Z]/.test(name)) { _.warn( 'You seem to be using camelCase for a component prop, ' + 'but HTML doesn\'t differentiate between upper and ' + 'lower case. You should use hyphen-delimited ' + 'attribute names. For more info see ' + 'http://vuejs.org/api/options.html#props' ) } if (!identRE.test(path)) { _.warn( 'Invalid prop key: "' + name + '". Prop keys ' + 'must be valid identifiers.' ) } value = attrs[name] /* jshint eqeqeq:false */ if (value != null) { prop = { name: name, raw: value, path: path } var tokens = textParser.parse(value) if (tokens) { if (el && el.nodeType === 1) { el.removeAttribute(name) } // important so that this doesn't get compiled // again as a normal attribute binding attrs[name] = null prop.dynamic = true prop.parentPath = textParser.tokensToExp(tokens) // check prop binding type. single = tokens.length === 1 literal = literalValueRE.test(prop.parentPath) // one time: {{* prop}} prop.oneTime = literal || (single && tokens[0].oneTime) // check one-way bindings if (!prop.oneTime) { settable = !literal && settablePathRE.test(prop.parentPath) // one way down: {{> prop}} prop.oneWayDown = !settable || (single && tokens[0].oneWay === 60) // < // one way up: {{< prop}} prop.oneWayUp = single && settable && tokens[0].oneWay === 62 // > } } props.push(prop) } } return makePropsLinkFn(props) } /** * Build a function that applies props to a vm. * * @param {Array} props * @return {Function} propsLinkFn */ function makePropsLinkFn (props) { return function propsLinkFn (vm, el) { var i = props.length var prop, path while (i--) { prop = props[i] path = prop.path if (prop.dynamic) { if (vm.$parent) { if (prop.oneTime) { // one time binding vm.$set(path, vm.$parent.$get(prop.parentPath)) } else { // dynamic binding vm._bindDir('prop', el, prop, propDef) } } else { _.warn( 'Cannot bind dynamic prop on a root instance' + ' with no parent: ' + prop.name + '="' + prop.raw + '"' ) } } else { // literal, just set once vm.$set(path, _.toNumber(prop.raw)) } } } } /** * Check for element directives (custom elements that should * be resovled as terminal directives). * * @param {Element} el * @param {Object} options */ function checkElementDirectives (el, options) { var tag = el.tagName.toLowerCase() var def = resolveAsset(options, 'elementDirectives', tag) if (def) { return makeTerminalNodeLinkFn(el, tag, '', options, def) } } /** * Check if an element is a component. If yes, return * a component link function. * * @param {Element} el * @param {Object} options * @return {Function|undefined} */ function checkComponent (el, options) { var componentId = _.checkComponent(el, options) if (componentId) { var componentLinkFn = function (vm, el, host) { vm._bindDir('component', el, { expression: componentId }, componentDef, host) } componentLinkFn.terminal = true return componentLinkFn } } /** * Check an element for terminal directives in fixed order. * If it finds one, return a terminal link function. * * @param {Element} el * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives (el, options) { if (_.attr(el, 'pre') !== null) { return skip } var value, dirName /* jshint boss: true */ for (var i = 0, l = terminalDirectives.length; i < l; i++) { dirName = terminalDirectives[i] if ((value = _.attr(el, dirName)) !== null) { return makeTerminalNodeLinkFn(el, dirName, value, options) } } } function skip () {} skip.terminal = true /** * Build a node link function for a terminal directive. * A terminal link function terminates the current * compilation recursion and handles compilation of the * subtree in the directive. * * @param {Element} el * @param {String} dirName * @param {String} value * @param {Object} options * @param {Object} [def] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn (el, dirName, value, options, def) { var descriptor = dirParser.parse(value)[0] // no need to call resolveAsset since terminal directives // are always internal def = def || options.directives[dirName] var fn = function terminalNodeLinkFn (vm, el, host) { vm._bindDir(dirName, el, descriptor, def, host) } fn.terminal = true return fn } /** * Compile the directives on an element and return a linker. * * @param {Element|Object} elOrAttrs * - could be an object of already-extracted * container attributes. * @param {Object} options * @return {Function} */ function compileDirectives (elOrAttrs, options) { var attrs = _.isPlainObject(elOrAttrs) ? mapToList(elOrAttrs) : elOrAttrs.attributes var i = attrs.length var dirs = [] var attr, name, value, dir, dirName, dirDef while (i--) { attr = attrs[i] name = attr.name value = attr.value if (value === null) continue if (name.indexOf(config.prefix) === 0) { dirName = name.slice(config.prefix.length) dirDef = resolveAsset(options, 'directives', dirName) _.assertAsset(dirDef, 'directive', dirName) if (dirDef) { dirs.push({ name: dirName, descriptors: dirParser.parse(value), def: dirDef }) } } else if (config.interpolate) { dir = collectAttrDirective(name, value, options) if (dir) { dirs.push(dir) } } } // sort by priority, LOW to HIGH if (dirs.length) { dirs.sort(directiveComparator) return makeNodeLinkFn(dirs) } } /** * Convert a map (Object) of attributes to an Array. * * @param {Object} map * @return {Array} */ function mapToList (map) { var list = [] for (var key in map) { list.push({ name: key, value: map[key] }) } return list } /** * Build a link function for all directives on a single node. * * @param {Array} directives * @return {Function} directivesLinkFn */ function makeNodeLinkFn (directives) { return function nodeLinkFn (vm, el, host) { // reverse apply because it's sorted low to high var i = directives.length var dir, j, k while (i--) { dir = directives[i] if (dir._link) { // custom link fn dir._link(vm, el) } else { k = dir.descriptors.length for (j = 0; j < k; j++) { vm._bindDir(dir.name, el, dir.descriptors[j], dir.def, host) } } } } } /** * Check an attribute for potential dynamic bindings, * and return a directive object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Object} */ function collectAttrDirective (name, value, options) { var tokens = textParser.parse(value) if (tokens) { var def = options.directives.attr var i = tokens.length var allOneTime = true while (i--) { var token = tokens[i] if (token.tag && !token.oneTime) { allOneTime = false } } return { def: def, _link: allOneTime ? function (vm, el) { el.setAttribute(name, vm.$interpolate(value)) } : function (vm, el) { var value = textParser.tokensToExp(tokens, vm) var desc = dirParser.parse(name + ':' + value)[0] vm._bindDir('attr', el, desc, def) } } } } /** * Directive priority sort comparator * * @param {Object} a * @param {Object} b */ function directiveComparator (a, b) { a = a.def.priority || 0 b = b.def.priority || 0 return a > b ? 1 : -1 } /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Cache = __webpack_require__(13) var templateCache = new Cache(1000) var idSelectorCache = new Cache(1000) var map = { _default : [0, '', ''], legend : [1, '<fieldset>', '</fieldset>'], tr : [2, '<table><tbody>', '</tbody></table>'], col : [ 2, '<table><tbody></tbody><colgroup>', '</colgroup></table>' ] } 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.g = map.defs = map.symbol = map.use = map.image = 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" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" ' + 'xmlns:ev="http://www.w3.org/2001/xml-events"' + 'version="1.1">', '</svg>' ] var tagRE = /<([\w:]+)/ var entityRE = /&\w+;/ /** * Convert a string template to a DocumentFragment. * Determines correct wrapping by tag types. Wrapping * strategy found in jQuery & component/domify. * * @param {String} templateString * @return {DocumentFragment} */ function stringToFragment (templateString) { // try a cache hit first var hit = templateCache.get(templateString) if (hit) { return hit } var frag = document.createDocumentFragment() var tagMatch = templateString.match(tagRE) var entityMatch = entityRE.test(templateString) if (!tagMatch && !entityMatch) { // text only, return a single text node. frag.appendChild( document.createTextNode(templateString) ) } else { var tag = tagMatch && tagMatch[1] var wrap = map[tag] || map._default var depth = wrap[0] var prefix = wrap[1] var suffix = wrap[2] var node = document.createElement('div') node.innerHTML = prefix + templateString.trim() + suffix while (depth--) { node = node.lastChild } var child /* jshint boss:true */ while (child = node.firstChild) { frag.appendChild(child) } } templateCache.put(templateString, frag) return frag } /** * Convert a template node to a DocumentFragment. * * @param {Node} node * @return {DocumentFragment} */ function nodeToFragment (node) { // if its a template tag and the browser supports it, // its content is already a document fragment. if ( _.isTemplate(node) && node.content instanceof DocumentFragment ) { return node.content } // script template if (node.tagName === 'SCRIPT') { return stringToFragment(node.textContent) } // normal node, clone it to avoid mutating the original var clone = exports.clone(node) var frag = document.createDocumentFragment() var child /* jshint boss:true */ while (child = clone.firstChild) { frag.appendChild(child) } return frag } // Test for the presence of the Safari template cloning bug // https://bugs.webkit.org/show_bug.cgi?id=137755 var hasBrokenTemplate = _.inBrowser ? (function () { var a = document.createElement('div') a.innerHTML = '<template>1</template>' return !a.cloneNode(true).firstChild.innerHTML })() : false // Test for IE10/11 textarea placeholder clone bug var hasTextareaCloneBug = _.inBrowser ? (function () { var t = document.createElement('textarea') t.placeholder = 't' return t.cloneNode(true).value === 't' })() : false /** * 1. Deal with Safari cloning nested <template> bug by * manually cloning all template instances. * 2. Deal with IE10/11 textarea placeholder bug by setting * the correct value after cloning. * * @param {Element|DocumentFragment} node * @return {Element|DocumentFragment} */ exports.clone = function (node) { var res = node.cloneNode(true) var i, original, cloned /* istanbul ignore if */ if (hasBrokenTemplate) { original = node.querySelectorAll('template') if (original.length) { cloned = res.querySelectorAll('template') i = cloned.length while (i--) { cloned[i].parentNode.replaceChild( original[i].cloneNode(true), cloned[i] ) } } } /* istanbul ignore if */ if (hasTextareaCloneBug) { if (node.tagName === 'TEXTAREA') { res.value = node.value } else { original = node.querySelectorAll('textarea') if (original.length) { cloned = res.querySelectorAll('textarea') i = cloned.length while (i--) { cloned[i].value = original[i].value } } } } return res } /** * Process the template option and normalizes it into a * a DocumentFragment that can be used as a partial or a * instance template. * * @param {*} template * Possible values include: * - DocumentFragment object * - Node object of type Template * - id selector: '#some-template-id' * - template string: '<div><span>{{msg}}</span></div>' * @param {Boolean} clone * @param {Boolean} noSelector * @return {DocumentFragment|undefined} */ exports.parse = function (template, clone, noSelector) { var node, frag // if the template is already a document fragment, // do nothing if (template instanceof DocumentFragment) { return clone ? template.cloneNode(true) : template } if (typeof template === 'string') { // id selector if (!noSelector && template.charAt(0) === '#') { // id selector can be cached too frag = idSelectorCache.get(template) if (!frag) { node = document.getElementById(template.slice(1)) if (node) { frag = nodeToFragment(node) // save selector to cache idSelectorCache.put(template, frag) } } } else { // normal string template frag = stringToFragment(template) } } else if (template.nodeType) { // a direct node frag = nodeToFragment(template) } return frag && clone ? exports.clone(frag) : frag } /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * A doubly linked list-based Least Recently Used (LRU) * cache. Will keep most recently used items while * discarding least recently used items when its limit is * reached. This is a bare-bone version of * Rasmus Andersson's js-lru: * * https://github.com/rsms/js-lru * * @param {Number} limit * @constructor */ function Cache (limit) { this.size = 0 this.limit = limit this.head = this.tail = undefined this._keymap = {} } var p = Cache.prototype /** * Put <value> into the cache associated with <key>. * Returns the entry which was removed to make room for * the new entry. Otherwise undefined is returned. * (i.e. if there was enough room already). * * @param {String} key * @param {*} value * @return {Entry|undefined} */ p.put = function (key, value) { var entry = { key:key, value:value } this._keymap[key] = entry if (this.tail) { this.tail.newer = entry entry.older = this.tail } else { this.head = entry } this.tail = entry if (this.size === this.limit) { return this.shift() } else { this.size++ } } /** * Purge the least recently used (oldest) entry from the * cache. Returns the removed entry or undefined if the * cache was empty. */ p.shift = function () { var entry = this.head if (entry) { this.head = this.head.newer this.head.older = undefined entry.newer = entry.older = undefined this._keymap[entry.key] = undefined } return entry } /** * Get and register recent use of <key>. Returns the value * associated with <key> or undefined if not in cache. * * @param {String} key * @param {Boolean} returnEntry * @return {Entry|*} */ p.get = function (key, returnEntry) { var entry = this._keymap[key] if (entry === undefined) return if (entry === this.tail) { return returnEntry ? entry : entry.value } // HEAD--------------TAIL // <.older .newer> // <--- add direction -- // A B C <D> E if (entry.newer) { if (entry === this.head) { this.head = entry.newer } entry.newer.older = entry.older // C <-- E. } if (entry.older) { entry.older.newer = entry.newer // C. --> E } entry.newer = undefined // D --x entry.older = this.tail // D. --> E if (this.tail) { this.tail.newer = entry // E. <-- D } this.tail = entry return returnEntry ? entry : entry.value } module.exports = Cache /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var Cache = __webpack_require__(13) var config = __webpack_require__(3) var dirParser = __webpack_require__(15) var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g var cache, tagRE, htmlRE, firstChar, lastChar /** * Escape a string so it can be used in a RegExp * constructor. * * @param {String} str */ function escapeRegex (str) { return str.replace(regexEscapeRE, '\\$&') } /** * Compile the interpolation tag regex. * * @return {RegExp} */ function compileRegex () { config._delimitersChanged = false var open = config.delimiters[0] var close = config.delimiters[1] firstChar = open.charAt(0) lastChar = close.charAt(close.length - 1) var firstCharRE = escapeRegex(firstChar) var lastCharRE = escapeRegex(lastChar) var openRE = escapeRegex(open) var closeRE = escapeRegex(close) tagRE = new RegExp( firstCharRE + '?' + openRE + '(.+?)' + closeRE + lastCharRE + '?', 'g' ) htmlRE = new RegExp( '^' + firstCharRE + openRE + '.*' + closeRE + lastCharRE + '$' ) // reset cache cache = new Cache(1000) } /** * Parse a template text string into an array of tokens. * * @param {String} text * @return {Array<Object> | null} * - {String} type * - {String} value * - {Boolean} [html] * - {Boolean} [oneTime] */ exports.parse = function (text) { if (config._delimitersChanged) { compileRegex() } var hit = cache.get(text) if (hit) { return hit } if (!tagRE.test(text)) { return null } var tokens = [] var lastIndex = tagRE.lastIndex = 0 var match, index, value, first, oneTime, oneWay /* jshint boss:true */ while (match = tagRE.exec(text)) { index = match.index // push text token if (index > lastIndex) { tokens.push({ value: text.slice(lastIndex, index) }) } // tag token first = match[1].charCodeAt(0) oneTime = first === 42 // * oneWay = first === 62 || first === 60 // > or < value = oneTime || oneWay ? match[1].slice(1) : match[1] tokens.push({ tag: true, value: value.trim(), html: htmlRE.test(match[0]), oneTime: oneTime, oneWay: oneWay ? first : 0 }) lastIndex = index + match[0].length } if (lastIndex < text.length) { tokens.push({ value: text.slice(lastIndex) }) } cache.put(text, tokens) return tokens } /** * Format a list of tokens into an expression. * e.g. tokens parsed from 'a {{b}} c' can be serialized * into one single expression as '"a " + b + " c"'. * * @param {Array} tokens * @param {Vue} [vm] * @return {String} */ exports.tokensToExp = function (tokens, vm) { return tokens.length > 1 ? tokens.map(function (token) { return formatToken(token, vm) }).join('+') : formatToken(tokens[0], vm, true) } /** * Format a single token. * * @param {Object} token * @param {Vue} [vm] * @param {Boolean} single * @return {String} */ function formatToken (token, vm, single) { return token.tag ? vm && token.oneTime ? '"' + vm.$eval(token.value) + '"' : inlineFilters(token.value, single) : '"' + token.value + '"' } /** * For an attribute with multiple interpolation tags, * e.g. attr="some-{{thing | filter}}", in order to combine * the whole thing into a single watchable expression, we * have to inline those filters. This function does exactly * that. This is a bit hacky but it avoids heavy changes * to directive parser and watcher mechanism. * * @param {String} exp * @param {Boolean} single * @return {String} */ var filterRE = /[^|]\|[^|]/ function inlineFilters (exp, single) { if (!filterRE.test(exp)) { return single ? exp : '(' + exp + ')' } else { var dir = dirParser.parse(exp)[0] if (!dir.filters) { return '(' + exp + ')' } else { return 'this._applyFilters(' + dir.expression + // value ',null,' + // oldValue (null for read) JSON.stringify(dir.filters) + // filter descriptors ',false)' // write? } } } /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Cache = __webpack_require__(13) var cache = new Cache(1000) var argRE = /^[^\{\?]+$|^'[^']*'$|^"[^"]*"$/ var filterTokenRE = /[^\s'"]+|'[^']+'|"[^"]+"/g var reservedArgRE = /^in$|^-?\d+/ /** * Parser state */ var str var c, i, l var inSingle var inDouble var curly var square var paren var begin var argIndex var dirs var dir var lastFilterIndex var arg /** * Push a directive object into the result Array */ function pushDir () { dir.raw = str.slice(begin, i).trim() if (dir.expression === undefined) { dir.expression = str.slice(argIndex, i).trim() } else if (lastFilterIndex !== begin) { pushFilter() } if (i === 0 || dir.expression) { dirs.push(dir) } } /** * Push a filter to the current directive object */ function pushFilter () { var exp = str.slice(lastFilterIndex, i).trim() var filter if (exp) { filter = {} var tokens = exp.match(filterTokenRE) filter.name = tokens[0] if (tokens.length > 1) { filter.args = tokens.slice(1).map(processFilterArg) } } if (filter) { (dir.filters = dir.filters || []).push(filter) } lastFilterIndex = i + 1 } /** * Check if an argument is dynamic and strip quotes. * * @param {String} arg * @return {Object} */ function processFilterArg (arg) { var stripped = reservedArgRE.test(arg) ? arg : _.stripQuotes(arg) return { value: stripped || arg, dynamic: !stripped } } /** * Parse a directive string into an Array of AST-like * objects representing directives. * * Example: * * "click: a = a + 1 | uppercase" will yield: * { * arg: 'click', * expression: 'a = a + 1', * filters: [ * { name: 'uppercase', args: null } * ] * } * * @param {String} str * @return {Array<Object>} */ exports.parse = function (s) { var hit = cache.get(s) if (hit) { return hit } // reset parser state str = s inSingle = inDouble = false curly = square = paren = begin = argIndex = 0 lastFilterIndex = 0 dirs = [] dir = {} arg = null for (i = 0, l = str.length; i < l; i++) { c = str.charCodeAt(i) if (inSingle) { // check single quote if (c === 0x27) inSingle = !inSingle } else if (inDouble) { // check double quote if (c === 0x22) inDouble = !inDouble } else if ( c === 0x2C && // comma !paren && !curly && !square ) { // reached the end of a directive pushDir() // reset & skip the comma dir = {} begin = argIndex = lastFilterIndex = i + 1 } else if ( c === 0x3A && // colon !dir.expression && !dir.arg ) { // argument arg = str.slice(begin, i).trim() // test for valid argument here // since we may have caught stuff like first half of // an object literal or a ternary expression. if (argRE.test(arg)) { argIndex = i + 1 dir.arg = _.stripQuotes(arg) || arg } } else if ( c === 0x7C && // pipe str.charCodeAt(i + 1) !== 0x7C && str.charCodeAt(i - 1) !== 0x7C ) { if (dir.expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1 dir.expression = str.slice(argIndex, i).trim() } else { // already has filter pushFilter() } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } } } if (i === 0 || begin !== i) { pushDir() } cache.put(s, dirs) return dirs } /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var Watcher = __webpack_require__(17) module.exports = { bind: function () { var child = this.vm var parent = child.$parent // passed in from compiler directly var prop = this._descriptor var childKey = prop.path var parentKey = prop.parentPath // simple lock to avoid circular updates. // without this it would stabilize too, but this makes // sure it doesn't cause other watchers to re-evaluate. var locked = false if (!prop.oneWayUp) { this.parentWatcher = new Watcher( parent, parentKey, function (val) { if (!locked) { locked = true // all props have been initialized already child[childKey] = val locked = false } }, { sync: true } ) // set the child initial value first, before setting // up the child watcher to avoid triggering it // immediately. child.$set(childKey, this.parentWatcher.value) } // only setup two-way binding if this is not a one-way // binding. if (!prop.oneWayDown) { this.childWatcher = new Watcher( child, childKey, function (val) { if (!locked) { locked = true parent.$set(parentKey, val) locked = false } }, { sync: true } ) // set initial value for one-way up binding if (prop.oneWayUp) { parent.$set(parentKey, this.childWatcher.value) } } }, unbind: function () { if (this.parentWatcher) { this.parentWatcher.teardown() } if (this.childWatcher) { this.childWatcher.teardown() } } } /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(3) var Observer = __webpack_require__(18) var expParser = __webpack_require__(22) var batcher = __webpack_require__(24) var uid = 0 /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. * * @param {Vue} vm * @param {String} expression * @param {Function} cb * @param {Object} options * - {Array} filters * - {Boolean} twoWay * - {Boolean} deep * - {Boolean} user * - {Boolean} sync * - {Function} [preProcess] * @constructor */ function Watcher (vm, expOrFn, cb, options) { var isFn = typeof expOrFn === 'function' this.vm = vm vm._watchers.push(this) this.expression = isFn ? '' : expOrFn this.cb = cb this.id = ++uid // uid for batching this.active = true options = options || {} this.deep = !!options.deep this.user = !!options.user this.twoWay = !!options.twoWay this.sync = !!options.sync this.filters = options.filters this.preProcess = options.preProcess this.deps = [] this.newDeps = [] // parse expression for getter/setter if (isFn) { this.getter = expOrFn this.setter = undefined } else { var res = expParser.parse(expOrFn, options.twoWay) this.getter = res.get this.setter = res.set } this.value = this.get() } var p = Watcher.prototype /** * Add a dependency to this directive. * * @param {Dep} dep */ p.addDep = function (dep) { var newDeps = this.newDeps var old = this.deps if (_.indexOf(newDeps, dep) < 0) { newDeps.push(dep) var i = _.indexOf(old, dep) if (i < 0) { dep.addSub(this) } else { old[i] = null } } } /** * Evaluate the getter, and re-collect dependencies. */ p.get = function () { this.beforeGet() var vm = this.vm var value try { value = this.getter.call(vm, vm) } catch (e) { if (config.warnExpressionErrors) { _.warn( 'Error when evaluating expression "' + this.expression + '"', e ) } } // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value) } if (this.preProcess) { value = this.preProcess(value) } if (this.filters) { value = vm._applyFilters(value, null, this.filters, false) } this.afterGet() return value } /** * Set the corresponding value with the setter. * * @param {*} value */ p.set = function (value) { var vm = this.vm if (this.filters) { value = vm._applyFilters( value, this.value, this.filters, true) } try { this.setter.call(vm, vm, value) } catch (e) { if (config.warnExpressionErrors) { _.warn( 'Error when evaluating setter "' + this.expression + '"', e ) } } } /** * Prepare for dependency collection. */ p.beforeGet = function () { Observer.setTarget(this) } /** * Clean up for dependency collection. */ p.afterGet = function () { Observer.setTarget(null) var i = this.deps.length while (i--) { var dep = this.deps[i] if (dep) { dep.removeSub(this) } } this.deps = this.newDeps this.newDeps = [] } /** * Subscriber interface. * Will be called when a dependency changes. */ p.update = function () { if (this.sync || !config.async) { this.run() } else { batcher.push(this) } } /** * Batcher job interface. * Will be called by the batcher. */ p.run = function () { if (this.active) { var value = this.get() if ( value !== this.value || Array.isArray(value) || this.deep ) { var oldValue = this.value this.value = value this.cb(value, oldValue) } } } /** * Remove self from all dependencies' subcriber list. */ p.teardown = function () { if (this.active) { // remove self from vm's watcher list // we can skip this if the vm if being destroyed // which can improve teardown performance. if (!this.vm._isBeingDestroyed) { this.vm._watchers.$remove(this) } var i = this.deps.length while (i--) { this.deps[i].removeSub(this) } this.active = false this.vm = this.cb = this.value = null } } /** * Recrusively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. * * @param {Object} obj */ function traverse (obj) { var key, val, i for (key in obj) { val = obj[key] if (_.isArray(val)) { i = val.length while (i--) traverse(val[i]) } else if (_.isObject(val)) { traverse(val) } } } module.exports = Watcher /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(3) var Dep = __webpack_require__(19) var arrayMethods = __webpack_require__(20) var arrayKeys = Object.getOwnPropertyNames(arrayMethods) __webpack_require__(21) var uid = 0 /** * Type enums */ var ARRAY = 0 var OBJECT = 1 /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. * * @param {Array|Object} value * @param {Number} type * @constructor */ function Observer (value, type) { this.id = ++uid this.value = value this.active = true this.deps = [] _.define(value, '__ob__', this) if (type === ARRAY) { var augment = config.proto && _.hasProto ? protoAugment : copyAugment augment(value, arrayMethods, arrayKeys) this.observeArray(value) } else if (type === OBJECT) { this.walk(value) } } // Static methods /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. * * @param {*} value * @return {Observer|undefined} * @static */ Observer.create = function (value) { if ( value && value.hasOwnProperty('__ob__') && value.__ob__ instanceof Observer ) { return value.__ob__ } else if (_.isArray(value)) { return new Observer(value, ARRAY) } else if ( _.isPlainObject(value) && !value._isVue // avoid Vue instance ) { return new Observer(value, OBJECT) } } /** * Set the target watcher that is currently being evaluated. * * @param {Watcher} watcher */ Observer.setTarget = function (watcher) { Dep.target = watcher } // Instance methods var p = Observer.prototype /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. Properties prefixed with `$` or `_` * and accessor properties are ignored. * * @param {Object} obj */ p.walk = function (obj) { var keys = Object.keys(obj) var i = keys.length var key, prefix while (i--) { key = keys[i] prefix = key.charCodeAt(0) if (prefix !== 0x24 && prefix !== 0x5F) { // skip $ or _ this.convert(key, obj[key]) } } } /** * Try to carete an observer for a child value, * and if value is array, link dep to the array. * * @param {*} val * @return {Dep|undefined} */ p.observe = function (val) { return Observer.create(val) } /** * Observe a list of Array items. * * @param {Array} items */ p.observeArray = function (items) { var i = items.length while (i--) { this.observe(items[i]) } } /** * Convert a property into getter/setter so we can emit * the events when the property is accessed/changed. * * @param {String} key * @param {*} val */ p.convert = function (key, val) { var ob = this var childOb = ob.observe(val) var dep = new Dep() if (childOb) { childOb.deps.push(dep) } Object.defineProperty(ob.value, key, { enumerable: true, configurable: true, get: function () { if (ob.active) { dep.depend() } return val }, set: function (newVal) { if (newVal === val) return // remove dep from old value var oldChildOb = val && val.__ob__ if (oldChildOb) { oldChildOb.deps.$remove(dep) } val = newVal // add dep to new value var newChildOb = ob.observe(newVal) if (newChildOb) { newChildOb.deps.push(dep) } dep.notify() } }) } /** * Notify change on all self deps on an observer. * This is called when a mutable value mutates. e.g. * when an Array's mutating methods are called, or an * Object's $add/$delete are called. */ p.notify = function () { var deps = this.deps for (var i = 0, l = deps.length; i < l; i++) { deps[i].notify() } } /** * Add an owner vm, so that when $add/$delete mutations * happen we can notify owner vms to proxy the keys and * digest the watchers. This is only called when the object * is observed as an instance's root $data. * * @param {Vue} vm */ p.addVm = function (vm) { (this.vms || (this.vms = [])).push(vm) } /** * Remove an owner vm. This is called when the object is * swapped out as an instance's $data object. * * @param {Vue} vm */ p.removeVm = function (vm) { this.vms.$remove(vm) } // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ * * @param {Object|Array} target * @param {Object} proto */ function protoAugment (target, src) { target.__proto__ = src } /** * Augment an target Object or Array by defining * hidden properties. * * @param {Object|Array} target * @param {Object} proto */ function copyAugment (target, src, keys) { var i = keys.length var key while (i--) { key = keys[i] _.define(target, key, src[key]) } } module.exports = Observer /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * A dep is an observable that can have multiple * directives subscribing to it. * * @constructor */ function Dep () { this.subs = [] } // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null var p = Dep.prototype /** * Add a directive subscriber. * * @param {Directive} sub */ p.addSub = function (sub) { this.subs.push(sub) } /** * Remove a directive subscriber. * * @param {Directive} sub */ p.removeSub = function (sub) { this.subs.$remove(sub) } /** * Add self as a dependency to the target watcher. */ p.depend = function () { if (Dep.target) { Dep.target.addDep(this) } } /** * Notify all subscribers of a new value. */ p.notify = function () { // stablize the subscriber list first var subs = _.toArray(this.subs) for (var i = 0, l = subs.length; i < l; i++) { subs[i].update() } } module.exports = Dep /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var arrayProto = Array.prototype var arrayMethods = Object.create(arrayProto) /** * Intercept mutating methods and emit events */ ;[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method] _.define(arrayMethods, method, function mutator () { // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length var args = new Array(i) while (i--) { args[i] = arguments[i] } var result = original.apply(this, args) var ob = this.__ob__ var inserted switch (method) { case 'push': inserted = args break case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) break } if (inserted) ob.observeArray(inserted) // notify change ob.notify() return result }) }) /** * Swap the element at the given index with a new value * and emits corresponding event. * * @param {Number} index * @param {*} val * @return {*} - replaced element */ _.define( arrayProto, '$set', function $set (index, val) { if (index >= this.length) { this.length = index + 1 } return this.splice(index, 1, val)[0] } ) /** * Convenience method to remove the element at given index. * * @param {Number} index * @param {*} val */ _.define( arrayProto, '$remove', function $remove (index) { /* istanbul ignore if */ if (!this.length) return if (typeof index !== 'number') { index = _.indexOf(this, index) } if (index > -1) { this.splice(index, 1) } } ) module.exports = arrayMethods /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var objProto = Object.prototype /** * Add a new property to an observed object * and emits corresponding event * * @param {String} key * @param {*} val * @public */ _.define( objProto, '$add', function $add (key, val) { if (this.hasOwnProperty(key)) return var ob = this.__ob__ if (!ob || _.isReserved(key)) { this[key] = val return } ob.convert(key, val) ob.notify() if (ob.vms) { var i = ob.vms.length while (i--) { var vm = ob.vms[i] vm._proxy(key) vm._digest() } } } ) /** * Set a property on an observed object, calling add to * ensure the property is observed. * * @param {String} key * @param {*} val * @public */ _.define( objProto, '$set', function $set (key, val) { this.$add(key, val) this[key] = val } ) /** * Deletes a property from an observed object * and emits corresponding event * * @param {String} key * @public */ _.define( objProto, '$delete', function $delete (key) { if (!this.hasOwnProperty(key)) return delete this[key] var ob = this.__ob__ if (!ob || _.isReserved(key)) { return } ob.notify() if (ob.vms) { var i = ob.vms.length while (i--) { var vm = ob.vms[i] vm._unproxy(key) vm._digest() } } } ) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Path = __webpack_require__(23) var Cache = __webpack_require__(13) var expressionCache = new Cache(1000) var allowedKeywords = 'Math,Date,this,true,false,null,undefined,Infinity,NaN,' + 'isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,' + 'encodeURIComponent,parseInt,parseFloat' var allowedKeywordsRE = new RegExp('^(' + allowedKeywords.replace(/,/g, '\\b|') + '\\b)') // keywords that don't make sense inside expressions var improperKeywords = 'break,case,class,catch,const,continue,debugger,default,' + 'delete,do,else,export,extends,finally,for,function,if,' + 'import,in,instanceof,let,return,super,switch,throw,try,' + 'var,while,with,yield,enum,await,implements,package,' + 'proctected,static,interface,private,public' var improperKeywordsRE = new RegExp('^(' + improperKeywords.replace(/,/g, '\\b|') + '\\b)') var wsRE = /\s/g var newlineRE = /\n/g var saveRE = /[\{,]\s*[\w\$_]+\s*:|('[^']*'|"[^"]*")|new |typeof |void /g var restoreRE = /"(\d+)"/g var pathTestRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/ var pathReplaceRE = /[^\w$\.]([A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\])*)/g var booleanLiteralRE = /^(true|false)$/ /** * Save / Rewrite / Restore * * When rewriting paths found in an expression, it is * possible for the same letter sequences to be found in * strings and Object literal property keys. Therefore we * remove and store these parts in a temporary array, and * restore them after the path rewrite. */ var saved = [] /** * Save replacer * * The save regex can match two possible cases: * 1. An opening object literal * 2. A string * If matched as a plain string, we need to escape its * newlines, since the string needs to be preserved when * generating the function body. * * @param {String} str * @param {String} isString - str if matched as a string * @return {String} - placeholder with index */ function save (str, isString) { var i = saved.length saved[i] = isString ? str.replace(newlineRE, '\\n') : str return '"' + i + '"' } /** * Path rewrite replacer * * @param {String} raw * @return {String} */ function rewrite (raw) { var c = raw.charAt(0) var path = raw.slice(1) if (allowedKeywordsRE.test(path)) { return raw } else { path = path.indexOf('"') > -1 ? path.replace(restoreRE, restore) : path return c + 'scope.' + path } } /** * Restore replacer * * @param {String} str * @param {String} i - matched save index * @return {String} */ function restore (str, i) { return saved[i] } /** * Rewrite an expression, prefixing all path accessors with * `scope.` and generate getter/setter functions. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ function compileExpFns (exp, needSet) { if (improperKeywordsRE.test(exp)) { _.warn( 'Avoid using reserved keywords in expression: ' + exp ) } // reset state saved.length = 0 // save strings and object literal keys var body = exp .replace(saveRE, save) .replace(wsRE, '') // rewrite all paths // pad 1 space here becaue the regex matches 1 extra char body = (' ' + body) .replace(pathReplaceRE, rewrite) .replace(restoreRE, restore) var getter = makeGetter(body) if (getter) { return { get: getter, body: body, set: needSet ? makeSetter(body) : null } } } /** * Compile getter setters for a simple path. * * @param {String} exp * @return {Function} */ function compilePathFns (exp) { var getter, path if (exp.indexOf('[') < 0) { // really simple path path = exp.split('.') path.raw = exp getter = Path.compileGetter(path) } else { // do the real parsing path = Path.parse(exp) getter = path.get } return { get: getter, // always generate setter for simple paths set: function (obj, val) { Path.set(obj, path, val) } } } /** * Build a getter function. Requires eval. * * We isolate the try/catch so it doesn't affect the * optimization of the parse function when it is not called. * * @param {String} body * @return {Function|undefined} */ function makeGetter (body) { try { return new Function('scope', 'return ' + body + ';') } catch (e) { _.warn( 'Invalid expression. ' + 'Generated function body: ' + body ) } } /** * Build a setter function. * * This is only needed in rare situations like "a[b]" where * a settable path requires dynamic evaluation. * * This setter function may throw error when called if the * expression body is not a valid left-hand expression in * assignment. * * @param {String} body * @return {Function|undefined} */ function makeSetter (body) { try { return new Function('scope', 'value', body + '=value;') } catch (e) { _.warn('Invalid setter function body: ' + body) } } /** * Check for setter existence on a cache hit. * * @param {Function} hit */ function checkSetter (hit) { if (!hit.set) { hit.set = makeSetter(hit.body) } } /** * Parse an expression into re-written getter/setters. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ exports.parse = function (exp, needSet) { exp = exp.trim() // try cache var hit = expressionCache.get(exp) if (hit) { if (needSet) { checkSetter(hit) } return hit } // we do a simple path check to optimize for them. // the check fails valid paths with unusal whitespaces, // but that's too rare and we don't care. // also skip boolean literals and paths that start with // global "Math" var res = exports.isSimplePath(exp) ? compilePathFns(exp) : compileExpFns(exp, needSet) expressionCache.put(exp, res) return res } /** * Check if an expression is a simple path. * * @param {String} exp * @return {Boolean} */ exports.isSimplePath = function (exp) { return pathTestRE.test(exp) && // don't treat true/false as paths !booleanLiteralRE.test(exp) && // Math constants e.g. Math.PI, Math.E etc. exp.slice(0, 5) !== 'Math.' } /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Cache = __webpack_require__(13) var pathCache = new Cache(1000) var identRE = exports.identRE = /^[$_a-zA-Z]+[\w$]*$/ /** * Path-parsing algorithm scooped from Polymer/observe-js */ var pathStateMachine = { 'beforePath': { 'ws': ['beforePath'], 'ident': ['inIdent', 'append'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'inPath': { 'ws': ['inPath'], '.': ['beforeIdent'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'beforeIdent': { 'ws': ['beforeIdent'], 'ident': ['inIdent', 'append'] }, 'inIdent': { 'ident': ['inIdent', 'append'], '0': ['inIdent', 'append'], 'number': ['inIdent', 'append'], 'ws': ['inPath', 'push'], '.': ['beforeIdent', 'push'], '[': ['beforeElement', 'push'], 'eof': ['afterPath', 'push'], ']': ['inPath', 'push'] }, 'beforeElement': { 'ws': ['beforeElement'], '0': ['afterZero', 'append'], 'number': ['inIndex', 'append'], "'": ['inSingleQuote', 'append', ''], '"': ['inDoubleQuote', 'append', ''], "ident": ['inIdent', 'append', '*'] }, 'afterZero': { 'ws': ['afterElement', 'push'], ']': ['inPath', 'push'] }, 'inIndex': { '0': ['inIndex', 'append'], 'number': ['inIndex', 'append'], 'ws': ['afterElement'], ']': ['inPath', 'push'] }, 'inSingleQuote': { "'": ['afterElement'], 'eof': 'error', 'else': ['inSingleQuote', 'append'] }, 'inDoubleQuote': { '"': ['afterElement'], 'eof': 'error', 'else': ['inDoubleQuote', 'append'] }, 'afterElement': { 'ws': ['afterElement'], ']': ['inPath', 'push'] } } function noop () {} /** * Determine the type of a character in a keypath. * * @param {Char} char * @return {String} type */ function getPathCharType (char) { if (char === undefined) { return 'eof' } var code = char.charCodeAt(0) switch(code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return char case 0x5F: // _ case 0x24: // $ return 'ident' case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws' } // a-z, A-Z if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A)) { return 'ident' } // 1-9 if (0x31 <= code && code <= 0x39) { return 'number' } return 'else' } /** * Parse a string path into an array of segments * Todo implement cache * * @param {String} path * @return {Array|undefined} */ function parsePath (path) { var keys = [] var index = -1 var mode = 'beforePath' var c, newChar, key, type, transition, action, typeMap var actions = { push: function() { if (key === undefined) { return } keys.push(key) key = undefined }, append: function() { if (key === undefined) { key = newChar } else { key += newChar } } } function maybeUnescapeQuote () { var nextChar = path[index + 1] if ((mode === 'inSingleQuote' && nextChar === "'") || (mode === 'inDoubleQuote' && nextChar === '"')) { index++ newChar = nextChar actions.append() return true } } while (mode) { index++ c = path[index] if (c === '\\' && maybeUnescapeQuote()) { continue } type = getPathCharType(c) typeMap = pathStateMachine[mode] transition = typeMap[type] || typeMap['else'] || 'error' if (transition === 'error') { return // parse error } mode = transition[0] action = actions[transition[1]] || noop newChar = transition[2] newChar = newChar === undefined ? c : newChar === '*' ? newChar + c : newChar action() if (mode === 'afterPath') { keys.raw = path return keys } } } /** * Format a accessor segment based on its type. * * @param {String} key * @return {Boolean} */ function formatAccessor (key) { if (identRE.test(key)) { // identifier return '.' + key } else if (+key === key >>> 0) { // bracket index return '[' + key + ']' } else if (key.charAt(0) === '*') { return '[o' + formatAccessor(key.slice(1)) + ']' } else { // bracket string return '["' + key.replace(/"/g, '\\"') + '"]' } } /** * Compiles a getter function with a fixed path. * The fixed path getter supresses errors. * * @param {Array} path * @return {Function} */ exports.compileGetter = function (path) { var body = 'return o' + path.map(formatAccessor).join('') return new Function('o', body) } /** * External parse that check for a cache hit first * * @param {String} path * @return {Array|undefined} */ exports.parse = function (path) { var hit = pathCache.get(path) if (!hit) { hit = parsePath(path) if (hit) { hit.get = exports.compileGetter(hit) pathCache.put(path, hit) } } return hit } /** * Get from an object from a path string * * @param {Object} obj * @param {String} path */ exports.get = function (obj, path) { path = exports.parse(path) if (path) { return path.get(obj) } } /** * Set on an object from a path * * @param {Object} obj * @param {String | Array} path * @param {*} val */ exports.set = function (obj, path, val) { var original = obj if (typeof path === 'string') { path = exports.parse(path) } if (!path || !_.isObject(obj)) { return false } var last, key for (var i = 0, l = path.length; i < l; i++) { last = obj key = path[i] if (key.charAt(0) === '*') { key = original[key.slice(1)] } if (i < l - 1) { obj = obj[key] if (!_.isObject(obj)) { obj = {} last.$add(key, obj) warnNonExistent(path) } } else { if (_.isArray(obj)) { obj.$set(key, val) } else if (key in obj) { obj[key] = val } else { obj.$add(key, val) warnNonExistent(path) } } } return true } function warnNonExistent (path) { _.warn( 'You are setting a non-existent path "' + path.raw + '" ' + 'on a vm instance. Consider pre-initializing the property ' + 'with the "data" option for more reliable reactivity ' + 'and better performance.' ) } /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var MAX_UPDATE_COUNT = 10 // we have two separate queues: one for directive updates // and one for user watcher registered via $watch(). // we want to guarantee directive updates to be called // before user watchers so that when user watchers are // triggered, the DOM would have already been in updated // state. var queue = [] var userQueue = [] var has = {} var waiting = false var flushing = false var internalQueueDepleted = false /** * Reset the batcher's state. */ function reset () { queue = [] userQueue = [] has = {} waiting = flushing = internalQueueDepleted = false } /** * Flush both queues and run the jobs. */ function flush () { flushing = true run(queue) internalQueueDepleted = true run(userQueue) reset() } /** * Run the jobs in a single queue. * * @param {Array} queue */ function run (queue) { // do not cache length because more jobs might be pushed // as we run existing jobs for (var i = 0; i < queue.length; i++) { queue[i].run() } } /** * Push a job into the job queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. * * @param {Object} job * properties: * - {String|Number} id * - {Function} run */ exports.push = function (job) { var id = job.id if (!id || !has[id] || flushing) { if (!has[id]) { has[id] = 1 } else { has[id]++ // detect possible infinite update loops if (has[id] > MAX_UPDATE_COUNT) { _.warn( 'You may have an infinite update loop for the ' + 'watcher with expression: "' + job.expression + '".' ) return } } // A user watcher callback could trigger another // directive update during the flushing; at that time // the directive queue would already have been run, so // we call that update immediately as it is pushed. if (flushing && !job.user && internalQueueDepleted) { job.run() return } ;(job.user ? userQueue : queue).push(job) if (!waiting) { waiting = true _.nextTick(flush) } } } /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var templateParser = __webpack_require__(12) module.exports = { isLiteral: true, /** * Setup. Two possible usages: * * - static: * v-component="comp" * * - dynamic: * v-component="{{currentView}}" */ bind: function () { if (!this.el.__vue__) { // create a ref anchor this.anchor = _.createAnchor('v-component') _.replace(this.el, this.anchor) // check keep-alive options. // If yes, instead of destroying the active vm when // hiding (v-if) or switching (dynamic literal) it, // we simply remove it from the DOM and save it in a // cache object, with its constructor id as the key. this.keepAlive = this._checkParam('keep-alive') != null // check ref this.refID = _.attr(this.el, 'ref') if (this.keepAlive) { this.cache = {} } // check inline-template if (this._checkParam('inline-template') !== null) { // extract inline template as a DocumentFragment this.template = _.extractContent(this.el, true) } // component resolution related state this._pendingCb = this.ctorId = this.Ctor = null // if static, build right now. if (!this._isDynamicLiteral) { this.resolveCtor(this.expression, _.bind(function () { var child = this.build() child.$before(this.anchor) this.setCurrent(child) }, this)) } else { // check dynamic component params this.readyEvent = this._checkParam('wait-for') this.transMode = this._checkParam('transition-mode') } } else { _.warn( 'v-component="' + this.expression + '" cannot be ' + 'used on an already mounted instance.' ) } }, /** * Public update, called by the watcher in the dynamic * literal scenario, e.g. v-component="{{view}}" */ update: function (value) { this.setComponent(value) }, /** * Switch dynamic components. May resolve the component * asynchronously, and perform transition based on * specified transition mode. Accepts a few additional * arguments specifically for vue-router. * * @param {String} value * @param {Object} data * @param {Function} afterBuild * @param {Function} afterTransition */ setComponent: function (value, data, afterBuild, afterTransition) { this.invalidatePending() if (!value) { // just remove current this.unbuild() this.remove(this.childVM, afterTransition) this.unsetCurrent() } else { this.resolveCtor(value, _.bind(function () { this.unbuild() var newComponent = this.build(data) /* istanbul ignore if */ if (afterBuild) afterBuild(newComponent) var self = this if (this.readyEvent) { newComponent.$once(this.readyEvent, function () { self.transition(newComponent, afterTransition) }) } else { this.transition(newComponent, afterTransition) } }, this)) } }, /** * Resolve the component constructor to use when creating * the child vm. */ resolveCtor: function (id, cb) { var self = this this._pendingCb = _.cancellable(function (ctor) { self.ctorId = id self.Ctor = ctor cb() }) this.vm._resolveComponent(id, this._pendingCb) }, /** * When the component changes or unbinds before an async * constructor is resolved, we need to invalidate its * pending callback. */ invalidatePending: function () { if (this._pendingCb) { this._pendingCb.cancel() this._pendingCb = null } }, /** * Instantiate/insert a new child vm. * If keep alive and has cached instance, insert that * instance; otherwise build a new one and cache it. * * @param {Object} [data] * @return {Vue} - the created instance */ build: function (data) { if (this.keepAlive) { var cached = this.cache[this.ctorId] if (cached) { return cached } } var vm = this.vm var el = templateParser.clone(this.el) if (this.Ctor) { var child = vm.$addChild({ el: el, data: data, template: this.template, // if no inline-template, then the compiled // linker can be cached for better performance. _linkerCachable: !this.template, _asComponent: true, _host: this._host, _isRouterView: this._isRouterView }, this.Ctor) if (this.keepAlive) { this.cache[this.ctorId] = child } return child } }, /** * Teardown the current child, but defers cleanup so * that we can separate the destroy and removal steps. */ unbuild: function () { var child = this.childVM if (!child || this.keepAlive) { return } // the sole purpose of `deferCleanup` is so that we can // "deactivate" the vm right now and perform DOM removal // later. child.$destroy(false, true) }, /** * Remove current destroyed child and manually do * the cleanup after removal. * * @param {Function} cb */ remove: function (child, cb) { var keepAlive = this.keepAlive if (child) { child.$remove(function () { if (!keepAlive) child._cleanup() if (cb) cb() }) } else if (cb) { cb() } }, /** * Actually swap the components, depending on the * transition mode. Defaults to simultaneous. * * @param {Vue} target * @param {Function} [cb] */ transition: function (target, cb) { var self = this var current = this.childVM this.unsetCurrent() this.setCurrent(target) switch (self.transMode) { case 'in-out': target.$before(self.anchor, function () { self.remove(current, cb) }) break case 'out-in': self.remove(current, function () { if (!target._isDestroyed) { target.$before(self.anchor, cb) } }) break default: self.remove(current) target.$before(self.anchor, cb) } }, /** * Set childVM and parent ref */ setCurrent: function (child) { this.childVM = child var refID = child._refID || this.refID if (refID) { this.vm.$[refID] = child } }, /** * Unset childVM and parent ref */ unsetCurrent: function () { var child = this.childVM this.childVM = null var refID = (child && child._refID) || this.refID if (refID) { this.vm.$[refID] = null } }, /** * Unbind. */ unbind: function () { this.invalidatePending() this.unbuild() // destroy all keep-alive cached instances if (this.cache) { for (var key in this.cache) { this.cache[key].$destroy() } this.cache = null } } } /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(3) var templateParser = __webpack_require__(12) /** * Process an element or a DocumentFragment based on a * instance option object. This allows us to transclude * a template node/fragment before the instance is created, * so the processed fragment can then be cloned and reused * in v-repeat. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ exports.transclude = function (el, options) { // extract container attributes to pass them down // to compiler, because they need to be compiled in // parent scope. we are mutating the options object here // assuming the same object will be used for compile // right after this. if (options) { options._containerAttrs = extractAttrs(el) } // for template tags, what we want is its content as // a documentFragment (for block instances) if (_.isTemplate(el)) { el = templateParser.parse(el) } if (options && options.template) { el = transcludeTemplate(el, options) } if (el instanceof DocumentFragment) { // anchors for block instance // passing in `persist: true` to avoid them being // discarded by IE during template cloning _.prepend(_.createAnchor('v-start', true), el) el.appendChild(_.createAnchor('v-end', true)) } return el } /** * Process the template option. * If the replace option is true this will swap the $el. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transcludeTemplate (el, options) { var template = options.template var frag = templateParser.parse(template, true) if (!frag) { _.warn('Invalid template option: ' + template) } else { options._content = _.extractContent(el) var replacer = frag.firstChild if (options.replace) { if ( frag.childNodes.length > 1 || replacer.nodeType !== 1 || // when root node has v-repeat, the instance ends up // having multiple top-level nodes, thus becoming a // block instance. (#835) replacer.hasAttribute(config.prefix + 'repeat') ) { return frag } else { options._replacerAttrs = extractAttrs(replacer) mergeAttrs(el, replacer) return replacer } } else { el.appendChild(frag) return el } } } /** * Helper to extract a component container's attribute names * into a map. * * @param {Element} el * @return {Object} */ function extractAttrs (el) { if (el.nodeType === 1 && el.hasAttributes()) { var attrs = el.attributes var res = {} var i = attrs.length while (i--) { res[attrs[i].name] = attrs[i].value } return res } } /** * Merge the attributes of two elements, and make sure * the class names are merged properly. * * @param {Element} from * @param {Element} to */ function mergeAttrs (from, to) { var attrs = from.attributes var i = attrs.length var name, value while (i--) { name = attrs[i].name value = attrs[i].value if (!to.hasAttribute(name)) { to.setAttribute(name, value) } else if (name === 'class') { to.className = to.className + ' ' + value } } } /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { // manipulation directives exports.text = __webpack_require__(29) exports.html = __webpack_require__(30) exports.attr = __webpack_require__(31) exports.show = __webpack_require__(32) exports['class'] = __webpack_require__(34) exports.el = __webpack_require__(35) exports.ref = __webpack_require__(36) exports.cloak = __webpack_require__(37) exports.style = __webpack_require__(28) exports.transition = __webpack_require__(38) // event listener directives exports.on = __webpack_require__(41) exports.model = __webpack_require__(42) // logic control directives exports.repeat = __webpack_require__(47) exports['if'] = __webpack_require__(48) // internal directives that should not be used directly // but we still want to expose them for advanced usage. exports._component = __webpack_require__(25) exports._prop = __webpack_require__(16) /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var prefixes = ['-webkit-', '-moz-', '-ms-'] var camelPrefixes = ['Webkit', 'Moz', 'ms'] var importantRE = /!important;?$/ var camelRE = /([a-z])([A-Z])/g var testEl = null var propCache = {} module.exports = { deep: true, update: function (value) { if (this.arg) { this.setProp(this.arg, value) } else { if (typeof value === 'object') { this.objectHandler(value) } else { this.el.style.cssText = value } } }, objectHandler: function (value) { // cache object styles so that only changed props // are actually updated. var cache = this.cache || (this.cache = {}) var prop, val for (prop in cache) { if (!(prop in value)) { this.setProp(prop, null) delete cache[prop] } } for (prop in value) { val = value[prop] if (val !== cache[prop]) { cache[prop] = val this.setProp(prop, val) } } }, setProp: function (prop, value) { prop = normalize(prop) if (!prop) return // unsupported prop // cast possible numbers/booleans into strings if (value != null) value += '' if (value) { var isImportant = importantRE.test(value) ? 'important' : '' if (isImportant) { value = value.replace(importantRE, '').trim() } this.el.style.setProperty(prop, value, isImportant) } else { this.el.style.removeProperty(prop) } } } /** * Normalize a CSS property name. * - cache result * - auto prefix * - camelCase -> dash-case * * @param {String} prop * @return {String} */ function normalize (prop) { if (propCache[prop]) { return propCache[prop] } var res = prefix(prop) propCache[prop] = propCache[res] = res return res } /** * Auto detect the appropriate prefix for a CSS property. * https://gist.github.com/paulirish/523692 * * @param {String} prop * @return {String} */ function prefix (prop) { prop = prop.replace(camelRE, '$1-$2').toLowerCase() var camel = _.camelize(prop) var upper = camel.charAt(0).toUpperCase() + camel.slice(1) if (!testEl) { testEl = document.createElement('div') } if (camel in testEl.style) { return prop } var i = prefixes.length var prefixed while (i--) { prefixed = camelPrefixes[i] + upper if (prefixed in testEl.style) { return prefixes[i] + prop } } } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { this.attr = this.el.nodeType === 3 ? 'nodeValue' : 'textContent' }, update: function (value) { this.el[this.attr] = _.toString(value) } } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var templateParser = __webpack_require__(12) module.exports = { bind: function () { // a comment node means this is a binding for // {{{ inline unescaped html }}} if (this.el.nodeType === 8) { // hold nodes this.nodes = [] // replace the placeholder with proper anchor this.anchor = _.createAnchor('v-html') _.replace(this.el, this.anchor) } }, update: function (value) { value = _.toString(value) if (this.nodes) { this.swap(value) } else { this.el.innerHTML = value } }, swap: function (value) { // remove old nodes var i = this.nodes.length while (i--) { _.remove(this.nodes[i]) } // convert new value to a fragment // do not attempt to retrieve from id selector var frag = templateParser.parse(value, true, true) // save a reference to these nodes so we can remove later this.nodes = _.toArray(frag.childNodes) _.before(frag, this.anchor) } } /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { // xlink var xlinkNS = 'http://www.w3.org/1999/xlink' var xlinkRE = /^xlink:/ module.exports = { priority: 850, update: function (value) { if (this.arg) { this.setAttr(this.arg, value) } else if (typeof value === 'object') { this.objectHandler(value) } }, objectHandler: function (value) { // cache object attrs so that only changed attrs // are actually updated. var cache = this.cache || (this.cache = {}) var attr, val for (attr in cache) { if (!(attr in value)) { this.setAttr(attr, null) delete cache[attr] } } for (attr in value) { val = value[attr] if (val !== cache[attr]) { cache[attr] = val this.setAttr(attr, val) } } }, setAttr: function (attr, value) { if (value || value === 0) { if (xlinkRE.test(attr)) { this.el.setAttributeNS(xlinkNS, attr, value) } else { this.el.setAttribute(attr, value) } } else { this.el.removeAttribute(attr) } } } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var transition = __webpack_require__(33) module.exports = function (value) { var el = this.el transition.apply(el, value ? 1 : -1, function () { el.style.display = value ? '' : 'none' }, this.vm) } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Append with transition. * * @oaram {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ exports.append = function (el, target, vm, cb) { apply(el, 1, function () { target.appendChild(el) }, vm, cb) } /** * InsertBefore with transition. * * @oaram {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ exports.before = function (el, target, vm, cb) { apply(el, 1, function () { _.before(el, target) }, vm, cb) } /** * Remove with transition. * * @oaram {Element} el * @param {Vue} vm * @param {Function} [cb] */ exports.remove = function (el, vm, cb) { apply(el, -1, function () { _.remove(el) }, vm, cb) } /** * Remove by appending to another parent with transition. * This is only used in block operations. * * @oaram {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ exports.removeThenAppend = function (el, target, vm, cb) { apply(el, -1, function () { target.appendChild(el) }, vm, cb) } /** * Append the childNodes of a fragment to target. * * @param {DocumentFragment} block * @param {Node} target * @param {Vue} vm */ exports.blockAppend = function (block, target, vm) { var nodes = _.toArray(block.childNodes) for (var i = 0, l = nodes.length; i < l; i++) { exports.before(nodes[i], target, vm) } } /** * Remove a block of nodes between two edge nodes. * * @param {Node} start * @param {Node} end * @param {Vue} vm */ exports.blockRemove = function (start, end, vm) { var node = start.nextSibling var next while (node !== end) { next = node.nextSibling exports.remove(node, vm) node = next } } /** * Apply transitions with an operation callback. * * @oaram {Element} el * @param {Number} direction * 1: enter * -1: leave * @param {Function} op - the actual DOM operation * @param {Vue} vm * @param {Function} [cb] */ var apply = exports.apply = function (el, direction, op, vm, cb) { var transition = el.__v_trans if ( !transition || // skip if there are no js hooks and CSS transition is // not supported (!transition.hooks && !_.transitionEndEvent) || // skip transitions for initial compile !vm._isCompiled || // if the vm is being manipulated by a parent directive // during the parent's compilation phase, skip the // animation. (vm.$parent && !vm.$parent._isCompiled) ) { op() if (cb) cb() return } var action = direction > 0 ? 'enter' : 'leave' transition[action](op, cb) } /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var addClass = _.addClass var removeClass = _.removeClass module.exports = { update: function (value) { if (this.arg) { // single toggle var method = value ? addClass : removeClass method(this.el, this.arg) } else { this.cleanup() if (value && typeof value === 'string') { // raw class text addClass(this.el, value) this.lastVal = value } else if (_.isPlainObject(value)) { // object toggle for (var key in value) { if (value[key]) { addClass(this.el, key) } else { removeClass(this.el, key) } } this.prevKeys = Object.keys(value) } } }, cleanup: function (value) { if (this.lastVal) { removeClass(this.el, this.lastVal) } if (this.prevKeys) { var i = this.prevKeys.length while (i--) { if (!value || !value[this.prevKeys[i]]) { removeClass(this.el, this.prevKeys[i]) } } } } } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { module.exports = { isLiteral: true, bind: function () { this.vm.$$[this.expression] = this.el }, unbind: function () { delete this.vm.$$[this.expression] } } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { isLiteral: true, bind: function () { var vm = this.el.__vue__ if (!vm) { _.warn( 'v-ref should only be used on a component root element.' ) return } // If we get here, it means this is a `v-ref` on a // child, because parent scope `v-ref` is stripped in // `v-component` already. So we just record our own ref // here - it will overwrite parent ref in `v-component`, // if any. vm._refID = this.expression } } /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var config = __webpack_require__(3) module.exports = { bind: function () { var el = this.el this.vm.$once('hook:compiled', function () { el.removeAttribute(config.prefix + 'cloak') }) } } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Transition = __webpack_require__(39) module.exports = { priority: 1000, isLiteral: true, bind: function () { if (!this._isDynamicLiteral) { this.update(this.expression) } }, update: function (id, oldId) { var el = this.el var vm = this.el.__vue__ || this.vm var hooks = _.resolveAsset(vm.$options, 'transitions', id) id = id || 'v' el.__v_trans = new Transition(el, id, hooks, vm) if (oldId) { _.removeClass(el, oldId + '-transition') } _.addClass(el, id + '-transition') } } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var queue = __webpack_require__(40) var addClass = _.addClass var removeClass = _.removeClass var transitionEndEvent = _.transitionEndEvent var animationEndEvent = _.animationEndEvent var transDurationProp = _.transitionProp + 'Duration' var animDurationProp = _.animationProp + 'Duration' var TYPE_TRANSITION = 1 var TYPE_ANIMATION = 2 /** * A Transition object that encapsulates the state and logic * of the transition. * * @param {Element} el * @param {String} id * @param {Object} hooks * @param {Vue} vm */ function Transition (el, id, hooks, vm) { this.el = el this.enterClass = id + '-enter' this.leaveClass = id + '-leave' this.hooks = hooks this.vm = vm // async state this.pendingCssEvent = this.pendingCssCb = this.cancel = this.pendingJsCb = this.op = this.cb = null this.typeCache = {} // bind var self = this ;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone'] .forEach(function (m) { self[m] = _.bind(self[m], self) }) } var p = Transition.prototype /** * Start an entering transition. * * 1. enter transition triggered * 2. call beforeEnter hook * 3. add enter class * 4. insert/show element * 5. call enter hook (with possible explicit js callback) * 6. reflow * 7. based on transition type: * - transition: * remove class now, wait for transitionend, * then done if there's no explicit js callback. * - animation: * wait for animationend, remove class, * then done if there's no explicit js callback. * - no css transition: * done now if there's no explicit js callback. * 8. wait for either done or js callback, then call * afterEnter hook. * * @param {Function} op - insert/show the element * @param {Function} [cb] */ p.enter = function (op, cb) { this.cancelPending() this.callHook('beforeEnter') this.cb = cb addClass(this.el, this.enterClass) op() this.callHookWithCb('enter') this.cancel = this.hooks && this.hooks.enterCancelled queue.push(this.enterNextTick) } /** * The "nextTick" phase of an entering transition, which is * to be pushed into a queue and executed after a reflow so * that removing the class can trigger a CSS transition. */ p.enterNextTick = function () { var type = this.getCssTransitionType(this.enterClass) var enterDone = this.enterDone if (type === TYPE_TRANSITION) { // trigger transition by removing enter class now removeClass(this.el, this.enterClass) this.setupCssCb(transitionEndEvent, enterDone) } else if (type === TYPE_ANIMATION) { this.setupCssCb(animationEndEvent, enterDone) } else if (!this.pendingJsCb) { enterDone() } } /** * The "cleanup" phase of an entering transition. */ p.enterDone = function () { this.cancel = this.pendingJsCb = null removeClass(this.el, this.enterClass) this.callHook('afterEnter') if (this.cb) this.cb() } /** * Start a leaving transition. * * 1. leave transition triggered. * 2. call beforeLeave hook * 3. add leave class (trigger css transition) * 4. call leave hook (with possible explicit js callback) * 5. reflow if no explicit js callback is provided * 6. based on transition type: * - transition or animation: * wait for end event, remove class, then done if * there's no explicit js callback. * - no css transition: * done if there's no explicit js callback. * 7. wait for either done or js callback, then call * afterLeave hook. * * @param {Function} op - remove/hide the element * @param {Function} [cb] */ p.leave = function (op, cb) { this.cancelPending() this.callHook('beforeLeave') this.op = op this.cb = cb addClass(this.el, this.leaveClass) this.callHookWithCb('leave') this.cancel = this.hooks && this.hooks.enterCancelled // only need to do leaveNextTick if there's no explicit // js callback if (!this.pendingJsCb) { queue.push(this.leaveNextTick) } } /** * The "nextTick" phase of a leaving transition. */ p.leaveNextTick = function () { var type = this.getCssTransitionType(this.leaveClass) if (type) { var event = type === TYPE_TRANSITION ? transitionEndEvent : animationEndEvent this.setupCssCb(event, this.leaveDone) } else { this.leaveDone() } } /** * The "cleanup" phase of a leaving transition. */ p.leaveDone = function () { this.cancel = this.pendingJsCb = null this.op() removeClass(this.el, this.leaveClass) this.callHook('afterLeave') if (this.cb) this.cb() } /** * Cancel any pending callbacks from a previously running * but not finished transition. */ p.cancelPending = function () { this.op = this.cb = null var hasPending = false if (this.pendingCssCb) { hasPending = true _.off(this.el, this.pendingCssEvent, this.pendingCssCb) this.pendingCssEvent = this.pendingCssCb = null } if (this.pendingJsCb) { hasPending = true this.pendingJsCb.cancel() this.pendingJsCb = null } if (hasPending) { removeClass(this.el, this.enterClass) removeClass(this.el, this.leaveClass) } if (this.cancel) { this.cancel.call(this.vm, this.el) this.cancel = null } } /** * Call a user-provided synchronous hook function. * * @param {String} type */ p.callHook = function (type) { if (this.hooks && this.hooks[type]) { this.hooks[type].call(this.vm, this.el) } } /** * Call a user-provided, potentially-async hook function. * We check for the length of arguments to see if the hook * expects a `done` callback. If true, the transition's end * will be determined by when the user calls that callback; * otherwise, the end is determined by the CSS transition or * animation. * * @param {String} type */ p.callHookWithCb = function (type) { var hook = this.hooks && this.hooks[type] if (hook) { if (hook.length > 1) { this.pendingJsCb = _.cancellable(this[type + 'Done']) } hook.call(this.vm, this.el, this.pendingJsCb) } } /** * Get an element's transition type based on the * calculated styles. * * @param {String} className * @return {Number} */ p.getCssTransitionType = function (className) { /* istanbul ignore if */ if ( !transitionEndEvent || // skip CSS transitions if page is not visible - // this solves the issue of transitionend events not // firing until the page is visible again. // pageVisibility API is supported in IE10+, same as // CSS transitions. document.hidden || // explicit js-only transition (this.hooks && this.hooks.css === false) ) { return } var type = this.typeCache[className] if (type) return type var inlineStyles = this.el.style var computedStyles = window.getComputedStyle(this.el) var transDuration = inlineStyles[transDurationProp] || computedStyles[transDurationProp] if (transDuration && transDuration !== '0s') { type = TYPE_TRANSITION } else { var animDuration = inlineStyles[animDurationProp] || computedStyles[animDurationProp] if (animDuration && animDuration !== '0s') { type = TYPE_ANIMATION } } if (type) { this.typeCache[className] = type } return type } /** * Setup a CSS transitionend/animationend callback. * * @param {String} event * @param {Function} cb */ p.setupCssCb = function (event, cb) { this.pendingCssEvent = event var self = this var el = this.el var onEnd = this.pendingCssCb = function (e) { if (e.target === el) { _.off(el, event, onEnd) self.pendingCssEvent = self.pendingCssCb = null if (!self.pendingJsCb && cb) { cb() } } } _.on(el, event, onEnd) } module.exports = Transition /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var queue = [] var queued = false /** * Push a job into the queue. * * @param {Function} job */ exports.push = function (job) { queue.push(job) if (!queued) { queued = true _.nextTick(flush) } } /** * Flush the queue, and do one forced reflow before * triggering transitions. */ function flush () { // Force layout var f = document.documentElement.offsetHeight for (var i = 0; i < queue.length; i++) { queue[i]() } queue = [] queued = false // dummy return, so js linters don't complain about // unused variable f return f } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { acceptStatement: true, priority: 700, bind: function () { // deal with iframes if ( this.el.tagName === 'IFRAME' && this.arg !== 'load' ) { var self = this this.iframeBind = function () { _.on(self.el.contentWindow, self.arg, self.handler) } _.on(this.el, 'load', this.iframeBind) } }, update: function (handler) { if (typeof handler !== 'function') { _.warn( 'Directive "v-on:' + this.expression + '" ' + 'expects a function value.' ) return } this.reset() var vm = this.vm this.handler = function (e) { e.targetVM = vm vm.$event = e var res = handler(e) vm.$event = null return res } if (this.iframeBind) { this.iframeBind() } else { _.on(this.el, this.arg, this.handler) } }, reset: function () { var el = this.iframeBind ? this.el.contentWindow : this.el if (this.handler) { _.off(el, this.arg, this.handler) } }, unbind: function () { this.reset() _.off(this.el, 'load', this.iframeBind) } } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var handlers = { text: __webpack_require__(43), radio: __webpack_require__(44), select: __webpack_require__(45), checkbox: __webpack_require__(46) } module.exports = { priority: 800, twoWay: true, handlers: handlers, /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number * - TODO: more types may be supplied as a plugin */ bind: function () { // friendly warning... this.checkFilters() if (this.hasRead && !this.hasWrite) { _.warn( 'It seems you are using a read-only filter with ' + 'v-model. You might want to use a two-way filter ' + 'to ensure correct behavior.' ) } var el = this.el var tag = el.tagName var handler if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text } else if (tag === 'SELECT') { handler = handlers.select } else if (tag === 'TEXTAREA') { handler = handlers.text } else { _.warn('v-model does not support element type: ' + tag) return } handler.bind.call(this) this.update = handler.update this.unbind = handler.unbind }, /** * Check read/write filter stats. */ checkFilters: function () { var filters = this.filters if (!filters) return var i = filters.length while (i--) { var filter = _.resolveAsset(this.vm.$options, 'filters', filters[i].name) if (typeof filter === 'function' || filter.read) { this.hasRead = true } if (filter.write) { this.hasWrite = true } } } } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { var self = this var el = this.el // check params // - lazy: update model on "change" instead of "input" var lazy = this._checkParam('lazy') != null // - number: cast value into number when updating model. var number = this._checkParam('number') != null // - debounce: debounce the input listener var debounce = parseInt(this._checkParam('debounce'), 10) // handle composition events. // http://blog.evanyou.me/2014/01/03/composition-event/ // skip this for Android because it handles composition // events quite differently. Android doesn't trigger // composition events for language input methods e.g. // Chinese, but instead triggers them for spelling // suggestions... (see Discussion/#162) var composing = false if (!_.isAndroid) { this.onComposeStart = function () { composing = true } this.onComposeEnd = function () { composing = false // in IE11 the "compositionend" event fires AFTER // the "input" event, so the input handler is blocked // at the end... have to call it here. self.listener() } _.on(el,'compositionstart', this.onComposeStart) _.on(el,'compositionend', this.onComposeEnd) } function syncToModel () { var val = number ? _.toNumber(el.value) : el.value self.set(val) } // if the directive has filters, we need to // record cursor position and restore it after updating // the input with the filtered value. // also force update for type="range" inputs to enable // "lock in range" (see #506) if (this.hasRead || el.type === 'range') { this.listener = function () { if (composing) return var charsOffset // some HTML5 input types throw error here try { // record how many chars from the end of input // the cursor was at charsOffset = el.value.length - el.selectionStart } catch (e) {} // Fix IE10/11 infinite update cycle // https://github.com/yyx990803/vue/issues/592 /* istanbul ignore if */ if (charsOffset < 0) { return } syncToModel() _.nextTick(function () { // force a value update, because in // certain cases the write filters output the // same result for different input values, and // the Observer set events won't be triggered. var newVal = self._watcher.value self.update(newVal) if (charsOffset != null) { var cursorPos = _.toString(newVal).length - charsOffset el.setSelectionRange(cursorPos, cursorPos) } }) } } else { this.listener = function () { if (composing) return syncToModel() } } if (debounce) { this.listener = _.debounce(this.listener, debounce) } // Now attach the main listener this.event = lazy ? 'change' : 'input' // Support jQuery events, since jQuery.trigger() doesn't // trigger native events in some cases and some plugins // rely on $.trigger() // // We want to make sure if a listener is attached using // jQuery, it is also removed with jQuery, that's why // we do the check for each directive instance and // store that check result on itself. This also allows // easier test coverage control by unsetting the global // jQuery variable in tests. this.hasjQuery = typeof jQuery === 'function' if (this.hasjQuery) { jQuery(el).on(this.event, this.listener) } else { _.on(el, this.event, this.listener) } // IE9 doesn't fire input event on backspace/del/cut if (!lazy && _.isIE9) { this.onCut = function () { _.nextTick(self.listener) } this.onDel = function (e) { if (e.keyCode === 46 || e.keyCode === 8) { self.listener() } } _.on(el, 'cut', this.onCut) _.on(el, 'keyup', this.onDel) } // set initial value if present if ( el.hasAttribute('value') || (el.tagName === 'TEXTAREA' && el.value.trim()) ) { this._initValue = number ? _.toNumber(el.value) : el.value } }, update: function (value) { this.el.value = _.toString(value) }, unbind: function () { var el = this.el if (this.hasjQuery) { jQuery(el).off(this.event, this.listener) } else { _.off(el, this.event, this.listener) } if (this.onComposeStart) { _.off(el, 'compositionstart', this.onComposeStart) _.off(el, 'compositionend', this.onComposeEnd) } if (this.onCut) { _.off(el,'cut', this.onCut) _.off(el,'keyup', this.onDel) } } } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { var self = this var el = this.el this.listener = function () { self.set(el.value) } _.on(el, 'change', this.listener) if (el.checked) { this._initValue = el.value } }, update: function (value) { /* jshint eqeqeq: false */ this.el.checked = value == this.el.value }, unbind: function () { _.off(this.el, 'change', this.listener) } } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Watcher = __webpack_require__(17) var dirParser = __webpack_require__(15) module.exports = { bind: function () { var self = this var el = this.el // check options param var optionsParam = this._checkParam('options') if (optionsParam) { initOptions.call(this, optionsParam) } this.number = this._checkParam('number') != null this.multiple = el.hasAttribute('multiple') this.listener = function () { var value = self.multiple ? getMultiValue(el) : el.value value = self.number ? _.isArray(value) ? value.map(_.toNumber) : _.toNumber(value) : value self.set(value) } _.on(el, 'change', this.listener) checkInitialValue.call(this) }, update: function (value) { /* jshint eqeqeq: false */ var el = this.el el.selectedIndex = -1 var multi = this.multiple && _.isArray(value) var options = el.options var i = options.length var option while (i--) { option = options[i] option.selected = multi ? indexOf(value, option.value) > -1 : value == option.value } }, unbind: function () { _.off(this.el, 'change', this.listener) if (this.optionWatcher) { this.optionWatcher.teardown() } } } /** * Initialize the option list from the param. * * @param {String} expression */ function initOptions (expression) { var self = this var descriptor = dirParser.parse(expression)[0] function optionUpdateWatcher (value) { if (_.isArray(value)) { self.el.innerHTML = '' buildOptions(self.el, value) if (self._watcher) { self.update(self._watcher.value) } } else { _.warn('Invalid options value for v-model: ' + value) } } this.optionWatcher = new Watcher( this.vm, descriptor.expression, optionUpdateWatcher, { deep: true, filters: descriptor.filters } ) // update with initial value optionUpdateWatcher(this.optionWatcher.value) } /** * Build up option elements. IE9 doesn't create options * when setting innerHTML on <select> elements, so we have * to use DOM API here. * * @param {Element} parent - a <select> or an <optgroup> * @param {Array} options */ function buildOptions (parent, options) { var op, el for (var i = 0, l = options.length; i < l; i++) { op = options[i] if (!op.options) { el = document.createElement('option') if (typeof op === 'string') { el.text = el.value = op } else { /* jshint eqeqeq: false */ if (op.value != null) { el.value = op.value } el.text = op.text || op.value || '' if (op.disabled) { el.disabled = true } } } else { el = document.createElement('optgroup') el.label = op.label buildOptions(el, op.options) } parent.appendChild(el) } } /** * Check the initial value for selected options. */ function checkInitialValue () { var initValue var options = this.el.options for (var i = 0, l = options.length; i < l; i++) { if (options[i].hasAttribute('selected')) { if (this.multiple) { (initValue || (initValue = [])) .push(options[i].value) } else { initValue = options[i].value } } } if (typeof initValue !== 'undefined') { this._initValue = this.number ? _.toNumber(initValue) : initValue } } /** * Helper to extract a value array for select[multiple] * * @param {SelectElement} el * @return {Array} */ function getMultiValue (el) { return Array.prototype.filter .call(el.options, filterSelected) .map(getOptionValue) } function filterSelected (op) { return op.selected } function getOptionValue (op) { return op.value || op.text } /** * Native Array.indexOf uses strict equal, but in this * case we need to match string/numbers with soft equal. * * @param {Array} arr * @param {*} val */ function indexOf (arr, val) { /* jshint eqeqeq: false */ var i = arr.length while (i--) { if (arr[i] == val) return i } return -1 } /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { var self = this var el = this.el this.listener = function () { self.set(el.checked) } _.on(el, 'change', this.listener) if (el.checked) { this._initValue = el.checked } }, update: function (value) { this.el.checked = !!value }, unbind: function () { _.off(this.el, 'change', this.listener) } } /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var isObject = _.isObject var isPlainObject = _.isPlainObject var textParser = __webpack_require__(14) var expParser = __webpack_require__(22) var templateParser = __webpack_require__(12) var compiler = __webpack_require__(10) var uid = 0 // async component resolution states var UNRESOLVED = 0 var PENDING = 1 var RESOLVED = 2 var ABORTED = 3 module.exports = { /** * Setup. */ bind: function () { // uid as a cache identifier this.id = '__v_repeat_' + (++uid) // setup anchor nodes this.start = _.createAnchor('v-repeat-start') this.end = _.createAnchor('v-repeat-end') _.replace(this.el, this.end) _.before(this.start, this.end) // check if this is a block repeat this.template = _.isTemplate(this.el) ? templateParser.parse(this.el, true) : this.el // check other directives that need to be handled // at v-repeat level this.checkIf() this.checkRef() this.checkComponent() // check for trackby param this.idKey = this._checkParam('track-by') || this._checkParam('trackby') // 0.11.0 compat // check for transition stagger var stagger = +this._checkParam('stagger') this.enterStagger = +this._checkParam('enter-stagger') || stagger this.leaveStagger = +this._checkParam('leave-stagger') || stagger this.cache = Object.create(null) }, /** * Warn against v-if usage. */ checkIf: function () { if (_.attr(this.el, 'if') !== null) { _.warn( 'Don\'t use v-if with v-repeat. ' + 'Use v-show or the "filterBy" filter instead.' ) } }, /** * Check if v-ref/ v-el is also present. */ checkRef: function () { var refID = _.attr(this.el, 'ref') this.refID = refID ? this.vm.$interpolate(refID) : null var elId = _.attr(this.el, 'el') this.elId = elId ? this.vm.$interpolate(elId) : null }, /** * Check the component constructor to use for repeated * instances. If static we resolve it now, otherwise it * needs to be resolved at build time with actual data. */ checkComponent: function () { this.componentState = UNRESOLVED var options = this.vm.$options var id = _.checkComponent(this.el, options) if (!id) { // default constructor this.Ctor = _.Vue // inline repeats should inherit this.inherit = true // important: transclude with no options, just // to ensure block start and block end this.template = compiler.transclude(this.template) var copy = _.extend({}, options) copy._asComponent = false this._linkFn = compiler.compile(this.template, copy) } else { this.Ctor = null this.asComponent = true // check inline-template if (this._checkParam('inline-template') !== null) { // extract inline template as a DocumentFragment this.inlineTempalte = _.extractContent(this.el, true) } var tokens = textParser.parse(id) if (tokens) { // dynamic component to be resolved later var ctorExp = textParser.tokensToExp(tokens) this.ctorGetter = expParser.parse(ctorExp).get } else { // static this.componentId = id this.pendingData = null } } }, resolveComponent: function () { this.componentState = PENDING this.vm._resolveComponent(this.componentId, _.bind(function (Ctor) { if (this.componentState === ABORTED) { return } this.Ctor = Ctor this.componentState = RESOLVED this.realUpdate(this.pendingData) this.pendingData = null }, this)) }, /** * Resolve a dynamic component to use for an instance. * The tricky part here is that there could be dynamic * components depending on instance data. * * @param {Object} data * @param {Object} meta * @return {Function} */ resolveDynamicComponent: function (data, meta) { // create a temporary context object and copy data // and meta properties onto it. // use _.define to avoid accidentally overwriting scope // properties. var context = Object.create(this.vm) var key for (key in data) { _.define(context, key, data[key]) } for (key in meta) { _.define(context, key, meta[key]) } var id = this.ctorGetter.call(context, context) var Ctor = _.resolveAsset(this.vm.$options, 'components', id) _.assertAsset(Ctor, 'component', id) if (!Ctor.options) { _.warn( 'Async resolution is not supported for v-repeat ' + '+ dynamic component. (component: ' + id + ')' ) return _.Vue } return Ctor }, /** * Update. * This is called whenever the Array mutates. If we have * a component, we might need to wait for it to resolve * asynchronously. * * @param {Array|Number|String} data */ update: function (data) { if (this.componentId) { var state = this.componentState if (state === UNRESOLVED) { this.pendingData = data // once resolved, it will call realUpdate this.resolveComponent() } else if (state === PENDING) { this.pendingData = data } else if (state === RESOLVED) { this.realUpdate(data) } } else { this.realUpdate(data) } }, /** * The real update that actually modifies the DOM. * * @param {Array|Number|String} data */ realUpdate: function (data) { this.vms = this.diff(data, this.vms) // update v-ref if (this.refID) { this.vm.$[this.refID] = this.converted ? toRefObject(this.vms) : this.vms } if (this.elId) { this.vm.$$[this.elId] = this.vms.map(function (vm) { return vm.$el }) } }, /** * Diff, based on new data and old data, determine the * minimum amount of DOM manipulations needed to make the * DOM reflect the new data Array. * * The algorithm diffs the new data Array by storing a * hidden reference to an owner vm instance on previously * seen data. This allows us to achieve O(n) which is * better than a levenshtein distance based algorithm, * which is O(m * n). * * @param {Array} data * @param {Array} oldVms * @return {Array} */ diff: function (data, oldVms) { var idKey = this.idKey var converted = this.converted var start = this.start var end = this.end var inDoc = _.inDoc(start) var alias = this.arg var init = !oldVms var vms = new Array(data.length) var obj, raw, vm, i, l, primitive // First pass, go through the new Array and fill up // the new vms array. If a piece of data has a cached // instance for it, we reuse it. Otherwise build a new // instance. for (i = 0, l = data.length; i < l; i++) { obj = data[i] raw = converted ? obj.$value : obj primitive = !isObject(raw) vm = !init && this.getVm(raw, i, converted ? obj.$key : null) if (vm) { // reusable instance vm._reused = true vm.$index = i // update $index // update data for track-by or object repeat, // since in these two cases the data is replaced // rather than mutated. if (idKey || converted || primitive) { if (alias) { vm[alias] = raw } else if (_.isPlainObject(raw)) { vm.$data = raw } else { vm.$value = raw } } } else { // new instance vm = this.build(obj, i, true) vm._reused = false } vms[i] = vm // insert if this is first run if (init) { vm.$before(end) } } // if this is the first run, we're done. if (init) { return vms } // Second pass, go through the old vm instances and // destroy those who are not reused (and remove them // from cache) var removalIndex = 0 var totalRemoved = oldVms.length - vms.length for (i = 0, l = oldVms.length; i < l; i++) { vm = oldVms[i] if (!vm._reused) { this.uncacheVm(vm) vm.$destroy(false, true) // defer cleanup until removal this.remove(vm, removalIndex++, totalRemoved, inDoc) } } // final pass, move/insert new instances into the // right place. var targetPrev, prevEl, currentPrev var insertionIndex = 0 for (i = 0, l = vms.length; i < l; i++) { vm = vms[i] // this is the vm that we should be after targetPrev = vms[i - 1] prevEl = targetPrev ? targetPrev._staggerCb ? targetPrev._staggerAnchor : targetPrev._blockEnd || targetPrev.$el : start if (vm._reused && !vm._staggerCb) { currentPrev = findPrevVm(vm, start, this.id) if (currentPrev !== targetPrev) { this.move(vm, prevEl) } } else { // new instance, or still in stagger. // insert with updated stagger index. this.insert(vm, insertionIndex++, prevEl, inDoc) } vm._reused = false } return vms }, /** * Build a new instance and cache it. * * @param {Object} data * @param {Number} index * @param {Boolean} needCache */ build: function (data, index, needCache) { var meta = { $index: index } if (this.converted) { meta.$key = data.$key } var raw = this.converted ? data.$value : data var alias = this.arg if (alias) { data = {} data[alias] = raw } else if (!isPlainObject(raw)) { // non-object values data = {} meta.$value = raw } else { // default data = raw } // resolve constructor var Ctor = this.Ctor || this.resolveDynamicComponent(data, meta) var vm = this.vm.$addChild({ el: templateParser.clone(this.template), data: data, inherit: this.inherit, template: this.inlineTempalte, // repeater meta, e.g. $index, $key _meta: meta, // mark this as an inline-repeat instance _repeat: this.inherit, // is this a component? _asComponent: this.asComponent, // linker cachable if no inline-template _linkerCachable: !this.inlineTempalte, // transclusion host _host: this._host, // pre-compiled linker for simple repeats _linkFn: this._linkFn, // identifier, shows that this vm belongs to this collection _repeatId: this.id }, Ctor) // cache instance if (needCache) { this.cacheVm(raw, vm, index, this.converted ? meta.$key : null) } // sync back changes for two-way bindings of primitive values var type = typeof raw var dir = this if ( this.rawType === 'object' && (type === 'string' || type === 'number') ) { vm.$watch(alias || '$value', function (val) { if (dir.filters) { _.warn( 'You seem to be mutating the $value reference of ' + 'a v-repeat instance (likely through v-model) ' + 'and filtering the v-repeat at the same time. ' + 'This will not work properly with an Array of ' + 'primitive values. Please use an Array of ' + 'Objects instead.' ) } dir._withLock(function () { if (dir.converted) { dir.rawValue[vm.$key] = val } else { dir.rawValue.$set(vm.$index, val) } }) }) } return vm }, /** * Unbind, teardown everything */ unbind: function () { this.componentState = ABORTED if (this.refID) { this.vm.$[this.refID] = null } if (this.vms) { var i = this.vms.length var vm while (i--) { vm = this.vms[i] this.uncacheVm(vm) vm.$destroy() } } }, /** * Cache a vm instance based on its data. * * If the data is an object, we save the vm's reference on * the data object as a hidden property. Otherwise we * cache them in an object and for each primitive value * there is an array in case there are duplicates. * * @param {Object} data * @param {Vue} vm * @param {Number} index * @param {String} [key] */ cacheVm: function (data, vm, index, key) { var idKey = this.idKey var cache = this.cache var primitive = !isObject(data) var id if (key || idKey || primitive) { id = idKey ? idKey === '$index' ? index : data[idKey] : (key || index) if (!cache[id]) { cache[id] = vm } else if (!primitive && idKey !== '$index') { _.warn('Duplicate track-by key in v-repeat: ' + id) } } else { id = this.id if (data.hasOwnProperty(id)) { if (data[id] === null) { data[id] = vm } else { _.warn( 'Duplicate objects are not supported in v-repeat ' + 'when using components or transitions.' ) } } else { _.define(data, id, vm) } } vm._raw = data }, /** * Try to get a cached instance from a piece of data. * * @param {Object} data * @param {Number} index * @param {String} [key] * @return {Vue|undefined} */ getVm: function (data, index, key) { var idKey = this.idKey var primitive = !isObject(data) if (key || idKey || primitive) { var id = idKey ? idKey === '$index' ? index : data[idKey] : (key || index) return this.cache[id] } else { return data[this.id] } }, /** * Delete a cached vm instance. * * @param {Vue} vm */ uncacheVm: function (vm) { var data = vm._raw var idKey = this.idKey var index = vm.$index var key = vm.$key var primitive = !isObject(data) if (idKey || key || primitive) { var id = idKey ? idKey === '$index' ? index : data[idKey] : (key || index) this.cache[id] = null } else { data[this.id] = null vm._raw = null } }, /** * Pre-process the value before piping it through the * filters, and convert non-Array objects to arrays. * * This function will be bound to this directive instance * and passed into the watcher. * * @param {*} value * @return {Array} * @private */ _preProcess: function (value) { // regardless of type, store the un-filtered raw value. this.rawValue = value var type = this.rawType = typeof value if (!isPlainObject(value)) { this.converted = false if (type === 'number') { value = range(value) } else if (type === 'string') { value = _.toArray(value) } return value || [] } else { // convert plain object to array. var keys = Object.keys(value) var i = keys.length var res = new Array(i) var key while (i--) { key = keys[i] res[i] = { $key: key, $value: value[key] } } this.converted = true return res } }, /** * Insert an instance. * * @param {Vue} vm * @param {Number} index * @param {Node} prevEl * @param {Boolean} inDoc */ insert: function (vm, index, prevEl, inDoc) { if (vm._staggerCb) { vm._staggerCb.cancel() vm._staggerCb = null } var staggerAmount = this.getStagger(vm, index, null, 'enter') if (inDoc && staggerAmount) { // create an anchor and insert it synchronously, // so that we can resolve the correct order without // worrying about some elements not inserted yet var anchor = vm._staggerAnchor if (!anchor) { anchor = vm._staggerAnchor = _.createAnchor('stagger-anchor') anchor.__vue__ = vm } _.after(anchor, prevEl) var op = vm._staggerCb = _.cancellable(function () { vm._staggerCb = null vm.$before(anchor) _.remove(anchor) }) setTimeout(op, staggerAmount) } else { vm.$after(prevEl) } }, /** * Move an already inserted instance. * * @param {Vue} vm * @param {Node} prevEl */ move: function (vm, prevEl) { vm.$after(prevEl, null, false) }, /** * Remove an instance. * * @param {Vue} vm * @param {Number} index * @param {Boolean} inDoc */ remove: function (vm, index, total, inDoc) { if (vm._staggerCb) { vm._staggerCb.cancel() vm._staggerCb = null // it's not possible for the same vm to be removed // twice, so if we have a pending stagger callback, // it means this vm is queued for enter but removed // before its transition started. Since it is already // destroyed, we can just leave it in detached state. return } var staggerAmount = this.getStagger(vm, index, total, 'leave') if (inDoc && staggerAmount) { var op = vm._staggerCb = _.cancellable(function () { vm._staggerCb = null remove() }) setTimeout(op, staggerAmount) } else { remove() } function remove () { vm.$remove(function () { vm._cleanup() }) } }, /** * Get the stagger amount for an insertion/removal. * * @param {Vue} vm * @param {Number} index * @param {String} type * @param {Number} total */ getStagger: function (vm, index, total, type) { type = type + 'Stagger' var transition = vm.$el.__v_trans var hooks = transition && transition.hooks var hook = hooks && (hooks[type] || hooks.stagger) return hook ? hook.call(vm, index, total) : index * this[type] } } /** * Helper to find the previous element that is an instance * root node. This is necessary because a destroyed vm's * element could still be lingering in the DOM before its * leaving transition finishes, but its __vue__ reference * should have been removed so we can skip them. * * If this is a block repeat, we want to make sure we only * return vm that is bound to this v-repeat. (see #929) * * @param {Vue} vm * @param {Comment|Text} anchor * @return {Vue} */ function findPrevVm (vm, anchor, id) { var el = vm.$el.previousSibling while ( (!el.__vue__ || el.__vue__.$options._repeatId !== id) && el !== anchor ) { el = el.previousSibling } return el.__vue__ } /** * Create a range array from given number. * * @param {Number} n * @return {Array} */ function range (n) { var i = -1 var ret = new Array(n) while (++i < n) { ret[i] = i } return ret } /** * Convert a vms array to an object ref for v-ref on an * Object value. * * @param {Array} vms * @return {Object} */ function toRefObject (vms) { var ref = {} for (var i = 0, l = vms.length; i < l; i++) { ref[vms[i].$key] = vms[i] } return ref } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var compiler = __webpack_require__(10) var templateParser = __webpack_require__(12) var transition = __webpack_require__(33) module.exports = { bind: function () { var el = this.el if (!el.__vue__) { this.start = _.createAnchor('v-if-start') this.end = _.createAnchor('v-if-end') _.replace(el, this.end) _.before(this.start, this.end) if (_.isTemplate(el)) { this.template = templateParser.parse(el, true) } else { this.template = document.createDocumentFragment() this.template.appendChild(templateParser.clone(el)) } // compile the nested partial this.linker = compiler.compile( this.template, this.vm.$options, true ) } else { this.invalid = true _.warn( 'v-if="' + this.expression + '" cannot be ' + 'used on an already mounted instance.' ) } }, update: function (value) { if (this.invalid) return if (value) { // avoid duplicate compiles, since update() can be // called with different truthy values if (!this.unlink) { this.compile() } } else { this.teardown() } }, compile: function () { var vm = this.vm var frag = templateParser.clone(this.template) // the linker is not guaranteed to be present because // this function might get called by v-partial this.unlink = this.linker(vm, frag) transition.blockAppend(frag, this.end, vm) // call attached for all the child components created // during the compilation if (_.inDoc(vm.$el)) { var children = this.getContainedComponents() if (children) children.forEach(callAttach) } }, teardown: function () { if (!this.unlink) return // collect children beforehand var children if (_.inDoc(this.vm.$el)) { children = this.getContainedComponents() } transition.blockRemove(this.start, this.end, this.vm) if (children) children.forEach(callDetach) this.unlink() this.unlink = null }, getContainedComponents: function () { var vm = this.vm var start = this.start.nextSibling var end = this.end var selfCompoents = vm._children.length && vm._children.filter(contains) var transComponents = vm._transCpnts && vm._transCpnts.filter(contains) function contains (c) { var cur = start var next while (next !== end) { next = cur.nextSibling if ( cur === c.$el || cur.contains && cur.contains(c.$el) ) { return true } cur = next } return false } return selfCompoents ? transComponents ? selfCompoents.concat(transComponents) : selfCompoents : transComponents }, unbind: function () { if (this.unlink) this.unlink() } } function callAttach (child) { if (!child._isAttached) { child._callHook('attached') } } function callDetach (child) { if (child._isAttached) { child._callHook('detached') } } /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Stringify value. * * @param {Number} indent */ exports.json = { read: function (value, indent) { return typeof value === 'string' ? value : JSON.stringify(value, null, Number(indent) || 2) }, write: function (value) { try { return JSON.parse(value) } catch (e) { return value } } } /** * 'abc' => 'Abc' */ exports.capitalize = function (value) { if (!value && value !== 0) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } /** * 'abc' => 'ABC' */ exports.uppercase = function (value) { return (value || value === 0) ? value.toString().toUpperCase() : '' } /** * 'AbC' => 'abc' */ exports.lowercase = function (value) { return (value || value === 0) ? value.toString().toLowerCase() : '' } /** * 12345 => $12,345.00 * * @param {String} sign */ var digitsRE = /(\d{3})(?=\d)/g exports.currency = function (value, sign) { value = parseFloat(value) if (!isFinite(value) || (!value && value !== 0)) return '' sign = sign || '$' var s = Math.floor(Math.abs(value)).toString(), i = s.length % 3, h = i > 0 ? (s.slice(0, i) + (s.length > 3 ? ',' : '')) : '', v = Math.abs(parseInt((value * 100) % 100, 10)), f = '.' + (v < 10 ? ('0' + v) : v) return (value < 0 ? '-' : '') + sign + h + s.slice(i).replace(digitsRE, '$1,') + f } /** * 'item' => 'items' * * @params * an array of strings corresponding to * the single, double, triple ... forms of the word to * be pluralized. When the number to be pluralized * exceeds the length of the args, it will use the last * entry in the array. * * e.g. ['single', 'double', 'triple', 'multiple'] */ exports.pluralize = function (value) { var args = _.toArray(arguments, 1) return args.length > 1 ? (args[value % 10 - 1] || args[args.length - 1]) : (args[0] + (value === 1 ? '' : 's')) } /** * A special filter that takes a handler function, * wraps it so it only gets triggered on specific * keypresses. v-on only. * * @param {String} key */ var keyCodes = { enter : 13, tab : 9, 'delete' : 46, up : 38, left : 37, right : 39, down : 40, esc : 27 } exports.key = function (handler, key) { if (!handler) return var code = keyCodes[key] if (!code) { code = parseInt(key, 10) } return function (e) { if (e.keyCode === code) { return handler.call(this, e) } } } // expose keycode hash exports.key.keyCodes = keyCodes /** * Install special array filters */ _.extend(exports, __webpack_require__(50)) /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Path = __webpack_require__(23) /** * Filter filter for v-repeat * * @param {String} searchKey * @param {String} [delimiter] * @param {String} dataKey */ exports.filterBy = function (arr, search, delimiter, dataKey) { // allow optional `in` delimiter // because why not if (delimiter && delimiter !== 'in') { dataKey = delimiter } /* jshint eqeqeq: false */ if (search == null) { return arr } // cast to lowercase string search = ('' + search).toLowerCase() return arr.filter(function (item) { return dataKey ? contains(Path.get(item, dataKey), search) : contains(item, search) }) } /** * Filter filter for v-repeat * * @param {String} sortKey * @param {String} reverse */ exports.orderBy = function (arr, sortKey, reverse) { if (!sortKey) { return arr } var order = 1 if (arguments.length > 2) { if (reverse === '-1') { order = -1 } else { order = reverse ? -1 : 1 } } // sort on a copy to avoid mutating original array return arr.slice().sort(function (a, b) { if (sortKey !== '$key' && sortKey !== '$value') { if (a && '$value' in a) a = a.$value if (b && '$value' in b) b = b.$value } a = _.isObject(a) ? Path.get(a, sortKey) : a b = _.isObject(b) ? Path.get(b, sortKey) : b return a === b ? 0 : a > b ? order : -order }) } /** * String contain helper * * @param {*} val * @param {String} search */ function contains (val, search) { if (_.isPlainObject(val)) { for (var key in val) { if (contains(val[key], search)) { return true } } } else if (_.isArray(val)) { var i = val.length while (i--) { if (contains(val[i], search)) { return true } } } else if (val != null) { return val.toString().toLowerCase().indexOf(search) > -1 } } /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) // This is the elementDirective that handles <content> // transclusions. It relies on the raw content of an // instance being stored as `$options._content` during // the transclude phase. module.exports = { bind: function () { var vm = this.vm var contentOwner = vm // we need find the content owner, which is the closest // non-inline-repeater instance. while (contentOwner.$options._repeat) { contentOwner = contentOwner.$parent } var raw = contentOwner.$options._content var content if (!raw) { // fallback content // extract as a fragment content = _.extractContent(this.el, true) this.compile(content, vm) return } var parent = contentOwner.$parent var selector = this.el.getAttribute('select') if (!selector) { // default content // Importent: clone the rawContent before extracting // content because the <content> may be inside a v-if // and need to be compiled more than once. content = _.extractContent(raw.cloneNode(true), true) this.compile(content, parent, vm) } else { // select content selector = vm.$interpolate(selector) content = raw.querySelector(selector) // only allow top-level select if (content && content.parentNode === raw) { // same deal, clone the node for v-if content = content.cloneNode(true) this.compile(content, parent, vm) } } }, compile: function (content, owner, host) { if (content && owner) { this.unlink = owner.$compile(content, host) } if (content) { _.replace(this.el, content) } else { _.remove(this.el) } }, unbind: function () { if (this.unlink) { this.unlink() } } } /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var mergeOptions = __webpack_require__(1).mergeOptions /** * The main init sequence. This is called for every * instance, including ones that are created from extended * constructors. * * @param {Object} options - this options object should be * the result of merging class * options and the options passed * in to the constructor. */ exports._init = function (options) { options = options || {} this.$el = null this.$parent = options._parent this.$root = options._root || this this.$ = {} // child vm references this.$$ = {} // element references this._watchers = [] // all watchers as an array this._directives = [] // all directives // a flag to avoid this being observed this._isVue = true // events bookkeeping this._events = {} // registered callbacks this._eventsCount = {} // for $broadcast optimization this._eventCancelled = false // for event cancellation // block instance properties this._isBlock = false this._blockStart = // @type {CommentNode} this._blockEnd = null // @type {CommentNode} // lifecycle state this._isCompiled = this._isDestroyed = this._isReady = this._isAttached = this._isBeingDestroyed = false this._unlinkFn = null // children this._children = [] this._childCtors = {} // transcluded components that belong to the parent. // need to keep track of them so that we can call // attached/detached hooks on them. this._transCpnts = [] this._host = options._host // push self into parent / transclusion host if (this.$parent) { this.$parent._children.push(this) } if (this._host) { this._host._transCpnts.push(this) } // props used in v-repeat diffing this._reused = false this._staggerOp = null // merge options. options = this.$options = mergeOptions( this.constructor.options, options, this ) // set data after merge. this._data = options.data || {} // initialize data observation and scope inheritance. this._initScope() // setup event system and option events. this._initEvents() // call created hook this._callHook('created') // if `el` option is passed, start compilation. if (options.el) { this.$mount(options.el) } } /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var inDoc = _.inDoc /** * Setup the instance's option events & watchers. * If the value is a string, we pull it from the * instance's methods by name. */ exports._initEvents = function () { var options = this.$options registerCallbacks(this, '$on', options.events) registerCallbacks(this, '$watch', options.watch) } /** * Register callbacks for option events and watchers. * * @param {Vue} vm * @param {String} action * @param {Object} hash */ function registerCallbacks (vm, action, hash) { if (!hash) return var handlers, key, i, j for (key in hash) { handlers = hash[key] if (_.isArray(handlers)) { for (i = 0, j = handlers.length; i < j; i++) { register(vm, action, key, handlers[i]) } } else { register(vm, action, key, handlers) } } } /** * Helper to register an event/watch callback. * * @param {Vue} vm * @param {String} action * @param {String} key * @param {*} handler */ function register (vm, action, key, handler) { var type = typeof handler if (type === 'function') { vm[action](key, handler) } else if (type === 'string') { var methods = vm.$options.methods var method = methods && methods[handler] if (method) { vm[action](key, method) } else { _.warn( 'Unknown method: "' + handler + '" when ' + 'registering callback for ' + action + ': "' + key + '".' ) } } } /** * Setup recursive attached/detached calls */ exports._initDOMHooks = function () { this.$on('hook:attached', onAttached) this.$on('hook:detached', onDetached) } /** * Callback to recursively call attached hook on children */ function onAttached () { this._isAttached = true this._children.forEach(callAttach) if (this._transCpnts.length) { this._transCpnts.forEach(callAttach) } } /** * Iterator to call attached hook * * @param {Vue} child */ function callAttach (child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached') } } /** * Callback to recursively call detached hook on children */ function onDetached () { this._isAttached = false this._children.forEach(callDetach) if (this._transCpnts.length) { this._transCpnts.forEach(callDetach) } } /** * Iterator to call detached hook * * @param {Vue} child */ function callDetach (child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached') } } /** * Trigger all handlers for a hook * * @param {String} hook */ exports._callHook = function (hook) { var handlers = this.$options[hook] if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(this) } } this.$emit('hook:' + hook) } /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Observer = __webpack_require__(18) var Dep = __webpack_require__(19) /** * Setup the scope of an instance, which contains: * - observed data * - computed properties * - user methods * - meta properties */ exports._initScope = function () { this._initData() this._initComputed() this._initMethods() this._initMeta() } /** * Initialize the data. */ exports._initData = function () { // proxy data on instance var data = this._data var i, key // make sure all props properties are observed var props = this.$options.props if (props) { i = props.length while (i--) { key = _.camelize(props[i]) if (!(key in data) && key !== '$data') { data[key] = undefined } } } var keys = Object.keys(data) i = keys.length while (i--) { key = keys[i] if (!_.isReserved(key)) { this._proxy(key) } } // observe data Observer.create(data).addVm(this) } /** * Swap the isntance's $data. Called in $data's setter. * * @param {Object} newData */ exports._setData = function (newData) { newData = newData || {} var oldData = this._data this._data = newData var keys, key, i // copy props. // this should only happen during a v-repeat of component // that also happens to have compiled props. var props = this.$options.props if (props) { i = props.length while (i--) { key = props[i] if (key !== '$data' && !newData.hasOwnProperty(key)) { newData.$set(key, oldData[key]) } } } // unproxy keys not present in new data keys = Object.keys(oldData) i = keys.length while (i--) { key = keys[i] if (!_.isReserved(key) && !(key in newData)) { this._unproxy(key) } } // proxy keys not already proxied, // and trigger change for changed values keys = Object.keys(newData) i = keys.length while (i--) { key = keys[i] if (!this.hasOwnProperty(key) && !_.isReserved(key)) { // new property this._proxy(key) } } oldData.__ob__.removeVm(this) Observer.create(newData).addVm(this) this._digest() } /** * Proxy a property, so that * vm.prop === vm._data.prop * * @param {String} key */ exports._proxy = function (key) { // need to store ref to self here // because these getter/setters might // be called by child instances! var self = this Object.defineProperty(self, key, { configurable: true, enumerable: true, get: function proxyGetter () { return self._data[key] }, set: function proxySetter (val) { self._data[key] = val } }) } /** * Unproxy a property. * * @param {String} key */ exports._unproxy = function (key) { delete this[key] } /** * Force update on every watcher in scope. */ exports._digest = function () { var i = this._watchers.length while (i--) { this._watchers[i].update() } var children = this._children i = children.length while (i--) { var child = children[i] if (child.$options.inherit) { child._digest() } } } /** * Setup computed properties. They are essentially * special getter/setters */ function noop () {} exports._initComputed = function () { var computed = this.$options.computed if (computed) { for (var key in computed) { var userDef = computed[key] var def = { enumerable: true, configurable: true } if (typeof userDef === 'function') { def.get = _.bind(userDef, this) def.set = noop } else { def.get = userDef.get ? _.bind(userDef.get, this) : noop def.set = userDef.set ? _.bind(userDef.set, this) : noop } Object.defineProperty(this, key, def) } } } /** * Setup instance methods. Methods must be bound to the * instance since they might be called by children * inheriting them. */ exports._initMethods = function () { var methods = this.$options.methods if (methods) { for (var key in methods) { this[key] = _.bind(methods[key], this) } } } /** * Initialize meta information like $index, $key & $value. */ exports._initMeta = function () { var metas = this.$options._meta if (metas) { for (var key in metas) { this._defineMeta(key, metas[key]) } } } /** * Define a meta property, e.g $index, $key, $value * which only exists on the vm instance but not in $data. * * @param {String} key * @param {*} value */ exports._defineMeta = function (key, value) { var dep = new Dep() Object.defineProperty(this, key, { enumerable: true, configurable: true, get: function metaGetter () { dep.depend() return value }, set: function metaSetter (val) { if (val !== value) { value = val dep.notify() } } }) } /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Directive = __webpack_require__(56) var compiler = __webpack_require__(10) /** * Transclude, compile and link element. * * If a pre-compiled linker is available, that means the * passed in element will be pre-transcluded and compiled * as well - all we need to do is to call the linker. * * Otherwise we need to call transclude/compile/link here. * * @param {Element} el * @return {Element} */ exports._compile = function (el) { var options = this.$options var host = this._host if (options._linkFn) { // pre-transcluded with linker, just use it this._initElement(el) this._unlinkFn = options._linkFn(this, el, host) } else { // transclude and init element // transclude can potentially replace original // so we need to keep reference; this step also injects // the template and caches the original attributes // on the container node and replacer node. var original = el el = compiler.transclude(el, options) this._initElement(el) // root is always compiled per-instance, because // container attrs and props can be different every time. var rootUnlinkFn = compiler.compileAndLinkRoot(this, el, options) // compile and link the rest var linker var ctor = this.constructor // component compilation can be cached // as long as it's not using inline-template if (options._linkerCachable) { linker = ctor.linker if (!linker) { linker = ctor.linker = compiler.compile(el, options) } } var contentUnlinkFn = linker ? linker(this, el) : compiler.compile(el, options)(this, el, host) this._unlinkFn = function () { rootUnlinkFn() // passing destroying: true to avoid searching and // splicing the directives contentUnlinkFn(true) } // finally replace original if (options.replace) { _.replace(original, el) } } return el } /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ exports._initElement = function (el) { if (el instanceof DocumentFragment) { this._isBlock = true this.$el = this._blockStart = el.firstChild this._blockEnd = el.lastChild // set persisted text anchors to empty if (this._blockStart.nodeType === 3) { this._blockStart.data = this._blockEnd.data = '' } this._blockFragment = el } else { this.$el = el } this.$el.__vue__ = this this._callHook('beforeCompile') } /** * Create and bind a directive to an element. * * @param {String} name - directive name * @param {Node} node - target node * @param {Object} desc - parsed directive descriptor * @param {Object} def - directive definition object * @param {Vue|undefined} host - transclusion host component */ exports._bindDir = function (name, node, desc, def, host) { this._directives.push( new Directive(name, node, this, desc, def, host) ) } /** * Teardown an instance, unobserves the data, unbind all the * directives, turn off all the event listeners, etc. * * @param {Boolean} remove - whether to remove the DOM node. * @param {Boolean} deferCleanup - if true, defer cleanup to * be called later */ exports._destroy = function (remove, deferCleanup) { if (this._isBeingDestroyed) { return } this._callHook('beforeDestroy') this._isBeingDestroyed = true var i // remove self from parent. only necessary // if parent is not being destroyed as well. var parent = this.$parent if (parent && !parent._isBeingDestroyed) { parent._children.$remove(this) } // same for transclusion host. var host = this._host if (host && !host._isBeingDestroyed) { host._transCpnts.$remove(this) } // destroy all children. i = this._children.length while (i--) { this._children[i].$destroy() } // teardown all directives. this also tearsdown all // directive-owned watchers. if (this._unlinkFn) { this._unlinkFn() } i = this._watchers.length while (i--) { this._watchers[i].teardown() } // remove reference to self on $el if (this.$el) { this.$el.__vue__ = null } // remove DOM element var self = this if (remove && this.$el) { this.$remove(function () { self._cleanup() }) } else if (!deferCleanup) { this._cleanup() } } /** * Clean up to ensure garbage collection. * This is called after the leave transition if there * is any. */ exports._cleanup = function () { // remove reference from data ob this._data.__ob__.removeVm(this) this._data = this._watchers = this.$el = this.$parent = this.$root = this._children = this._transCpnts = this._directives = null // call the last hook... this._isDestroyed = true this._callHook('destroyed') // turn off all instance listeners. this.$off() } /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(3) var Watcher = __webpack_require__(17) var textParser = __webpack_require__(14) var expParser = __webpack_require__(22) /** * A directive links a DOM element with a piece of data, * which is the result of evaluating an expression. * It registers a watcher with the expression and calls * the DOM update function when a change is triggered. * * @param {String} name * @param {Node} el * @param {Vue} vm * @param {Object} descriptor * - {String} expression * - {String} [arg] * - {Array<Object>} [filters] * @param {Object} def - directive definition object * @param {Vue|undefined} host - transclusion host target * @constructor */ function Directive (name, el, vm, descriptor, def, host) { // public this.name = name this.el = el this.vm = vm // copy descriptor props this.raw = descriptor.raw this.expression = descriptor.expression this.arg = descriptor.arg this.filters = descriptor.filters // private this._descriptor = descriptor this._host = host this._locked = false this._bound = false // init this._bind(def) } var p = Directive.prototype /** * Initialize the directive, mixin definition properties, * setup the watcher, call definition bind() and update() * if present. * * @param {Object} def */ p._bind = function (def) { if (this.name !== 'cloak' && this.el && this.el.removeAttribute) { this.el.removeAttribute(config.prefix + this.name) } if (typeof def === 'function') { this.update = def } else { _.extend(this, def) } this._watcherExp = this.expression this._checkDynamicLiteral() if (this.bind) { this.bind() } if (this._watcherExp && (this.update || this.twoWay) && (!this.isLiteral || this._isDynamicLiteral) && !this._checkStatement()) { // wrapped updater for context var dir = this var update = this._update = this.update ? function (val, oldVal) { if (!dir._locked) { dir.update(val, oldVal) } } : function () {} // noop if no update is provided // pre-process hook called before the value is piped // through the filters. used in v-repeat. var preProcess = this._preProcess ? _.bind(this._preProcess, this) : null var watcher = this._watcher = new Watcher( this.vm, this._watcherExp, update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess } ) if (this._initValue != null) { watcher.set(this._initValue) } else if (this.update) { this.update(watcher.value) } } this._bound = true } /** * check if this is a dynamic literal binding. * * e.g. v-component="{{currentView}}" */ p._checkDynamicLiteral = function () { var expression = this.expression if (expression && this.isLiteral) { var tokens = textParser.parse(expression) if (tokens) { var exp = textParser.tokensToExp(tokens) this.expression = this.vm.$get(exp) this._watcherExp = exp this._isDynamicLiteral = true } } } /** * Check if the directive is a function caller * and if the expression is a callable one. If both true, * we wrap up the expression and use it as the event * handler. * * e.g. v-on="click: a++" * * @return {Boolean} */ p._checkStatement = function () { var expression = this.expression if ( expression && this.acceptStatement && !expParser.isSimplePath(expression) ) { var fn = expParser.parse(expression).get var vm = this.vm var handler = function () { fn.call(vm, vm) } if (this.filters) { handler = vm._applyFilters(handler, null, this.filters) } this.update(handler) return true } } /** * Check for an attribute directive param, e.g. lazy * * @param {String} name * @return {String} */ p._checkParam = function (name) { var param = this.el.getAttribute(name) if (param !== null) { this.el.removeAttribute(name) } return param } /** * Teardown the watcher and call unbind. */ p._teardown = function () { if (this._bound) { this._bound = false if (this.unbind) { this.unbind() } if (this._watcher) { this._watcher.teardown() } this.vm = this.el = this._watcher = null } } /** * Set the corresponding value with the setter. * This should only be used in two-way directives * e.g. v-model. * * @param {*} value * @public */ p.set = function (value) { if (this.twoWay) { this._withLock(function () { this._watcher.set(value) }) } } /** * Execute a function while preventing that function from * triggering updates on this directive instance. * * @param {Function} fn */ p._withLock = function (fn) { var self = this self._locked = true fn.call(self) _.nextTick(function () { self._locked = false }) } module.exports = Directive /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Apply a list of filter (descriptors) to a value. * Using plain for loops here because this will be called in * the getter of any watcher with filters so it is very * performance sensitive. * * @param {*} value * @param {*} [oldValue] * @param {Array} filters * @param {Boolean} write * @return {*} */ exports._applyFilters = function (value, oldValue, filters, write) { var filter, fn, args, arg, offset, i, l, j, k for (i = 0, l = filters.length; i < l; i++) { filter = filters[i] fn = _.resolveAsset(this.$options, 'filters', filter.name) _.assertAsset(fn, 'filter', filter.name) if (!fn) continue fn = write ? fn.write : (fn.read || fn) if (typeof fn !== 'function') continue args = write ? [value, oldValue] : [value] offset = write ? 2 : 1 if (filter.args) { for (j = 0, k = filter.args.length; j < k; j++) { arg = filter.args[j] args[j + offset] = arg.dynamic ? this.$get(arg.value) : arg.value } } value = fn.apply(this, args) } return value } /** * Resolve a component, depending on whether the component * is defined normally or using an async factory function. * Resolves synchronously if already resolved, otherwise * resolves asynchronously and caches the resolved * constructor on the factory. * * @param {String} id * @param {Function} cb */ exports._resolveComponent = function (id, cb) { var factory = _.resolveAsset(this.$options, 'components', id) _.assertAsset(factory, 'component', id) // async component factory if (!factory.options) { if (factory.resolved) { // cached cb(factory.resolved) } else if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb) } else { factory.requested = true var cbs = factory.pendingCallbacks = [cb] factory(function resolve (res) { if (_.isPlainObject(res)) { res = _.Vue.extend(res) } // cache resolved factory.resolved = res // invoke callbacks for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res) } }, function reject (reason) { _.warn( 'Failed to resolve async component: ' + id + '. ' + (reason ? '\nReason: ' + reason : '') ) }) } } else { // normal component cb(factory) } } /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var Watcher = __webpack_require__(17) var Path = __webpack_require__(23) var textParser = __webpack_require__(14) var dirParser = __webpack_require__(15) var expParser = __webpack_require__(22) var filterRE = /[^|]\|[^|]/ /** * Get the value from an expression on this vm. * * @param {String} exp * @return {*} */ exports.$get = function (exp) { var res = expParser.parse(exp) if (res) { try { return res.get.call(this, this) } catch (e) {} } } /** * Set the value from an expression on this vm. * The expression must be a valid left-hand * expression in an assignment. * * @param {String} exp * @param {*} val */ exports.$set = function (exp, val) { var res = expParser.parse(exp, true) if (res && res.set) { res.set.call(this, this, val) } } /** * Add a property on the VM * * @param {String} key * @param {*} val */ exports.$add = function (key, val) { this._data.$add(key, val) } /** * Delete a property on the VM * * @param {String} key */ exports.$delete = function (key) { this._data.$delete(key) } /** * Watch an expression, trigger callback when its * value changes. * * @param {String} exp * @param {Function} cb * @param {Object} [options] * - {Boolean} deep * - {Boolean} immediate * - {Boolean} user * @return {Function} - unwatchFn */ exports.$watch = function (exp, cb, options) { var vm = this var wrappedCb = function (val, oldVal) { cb.call(vm, val, oldVal) } var watcher = new Watcher(vm, exp, wrappedCb, { deep: options && options.deep, user: !options || options.user !== false }) if (options && options.immediate) { wrappedCb(watcher.value) } return function unwatchFn () { watcher.teardown() } } /** * Evaluate a text directive, including filters. * * @param {String} text * @return {String} */ exports.$eval = function (text) { // check for filters. if (filterRE.test(text)) { var dir = dirParser.parse(text)[0] // the filter regex check might give false positive // for pipes inside strings, so it's possible that // we don't get any filters here var val = this.$get(dir.expression) return dir.filters ? this._applyFilters(val, null, dir.filters) : val } else { // no filter return this.$get(text) } } /** * Interpolate a piece of template text. * * @param {String} text * @return {String} */ exports.$interpolate = function (text) { var tokens = textParser.parse(text) var vm = this if (tokens) { return tokens.length === 1 ? vm.$eval(tokens[0].value) : tokens.map(function (token) { return token.tag ? vm.$eval(token.value) : token.value }).join('') } else { return text } } /** * Log instance data as a plain JS object * so that it is easier to inspect in console. * This method assumes console is available. * * @param {String} [path] */ exports.$log = function (path) { var data = path ? Path.get(this._data, path) : this._data if (data) { data = JSON.parse(JSON.stringify(data)) } console.log(data) } /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var transition = __webpack_require__(33) /** * Convenience on-instance nextTick. The callback is * auto-bound to the instance, and this avoids component * modules having to rely on the global Vue. * * @param {Function} fn */ exports.$nextTick = function (fn) { _.nextTick(fn, this) } /** * Append instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$appendTo = function (target, cb, withTransition) { return insert( this, target, cb, withTransition, append, transition.append ) } /** * Prepend instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$prependTo = function (target, cb, withTransition) { target = query(target) if (target.hasChildNodes()) { this.$before(target.firstChild, cb, withTransition) } else { this.$appendTo(target, cb, withTransition) } return this } /** * Insert instance before target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$before = function (target, cb, withTransition) { return insert( this, target, cb, withTransition, before, transition.before ) } /** * Insert instance after target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$after = function (target, cb, withTransition) { target = query(target) if (target.nextSibling) { this.$before(target.nextSibling, cb, withTransition) } else { this.$appendTo(target.parentNode, cb, withTransition) } return this } /** * Remove instance from DOM * * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$remove = function (cb, withTransition) { if (!this.$el.parentNode) { return cb && cb() } var inDoc = this._isAttached && _.inDoc(this.$el) // if we are not in document, no need to check // for transitions if (!inDoc) withTransition = false var op var self = this var realCb = function () { if (inDoc) self._callHook('detached') if (cb) cb() } if ( this._isBlock && !this._blockFragment.hasChildNodes() ) { op = withTransition === false ? append : transition.removeThenAppend blockOp(this, this._blockFragment, op, realCb) } else { op = withTransition === false ? remove : transition.remove op(this.$el, this, realCb) } return this } /** * Shared DOM insertion function. * * @param {Vue} vm * @param {Element} target * @param {Function} [cb] * @param {Boolean} [withTransition] * @param {Function} op1 - op for non-transition insert * @param {Function} op2 - op for transition insert * @return vm */ function insert (vm, target, cb, withTransition, op1, op2) { target = query(target) var targetIsDetached = !_.inDoc(target) var op = withTransition === false || targetIsDetached ? op1 : op2 var shouldCallHook = !targetIsDetached && !vm._isAttached && !_.inDoc(vm.$el) if (vm._isBlock) { blockOp(vm, target, op, cb) } else { op(vm.$el, target, vm, cb) } if (shouldCallHook) { vm._callHook('attached') } return vm } /** * Execute a transition operation on a block instance, * iterating through all its block nodes. * * @param {Vue} vm * @param {Node} target * @param {Function} op * @param {Function} cb */ function blockOp (vm, target, op, cb) { var current = vm._blockStart var end = vm._blockEnd var next while (next !== end) { next = current.nextSibling op(current, target, vm) current = next } op(end, target, vm, cb) } /** * Check for selectors * * @param {String|Element} el */ function query (el) { return typeof el === 'string' ? document.querySelector(el) : el } /** * Append operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function append (el, target, vm, cb) { target.appendChild(el) if (cb) cb() } /** * InsertBefore operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function before (el, target, vm, cb) { _.before(el, target) if (cb) cb() } /** * Remove operation that takes a callback. * * @param {Node} el * @param {Vue} vm - unused * @param {Function} [cb] */ function remove (el, vm, cb) { _.remove(el) if (cb) cb() } /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn */ exports.$on = function (event, fn) { (this._events[event] || (this._events[event] = [])) .push(fn) modifyListenerCount(this, event, 1) return this } /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn */ exports.$once = function (event, fn) { var self = this function on () { self.$off(event, on) fn.apply(this, arguments) } on.fn = fn this.$on(event, on) return this } /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn */ exports.$off = function (event, fn) { var cbs // all if (!arguments.length) { if (this.$parent) { for (event in this._events) { cbs = this._events[event] if (cbs) { modifyListenerCount(this, event, -cbs.length) } } } this._events = {} return this } // specific event cbs = this._events[event] if (!cbs) { return this } if (arguments.length === 1) { modifyListenerCount(this, event, -cbs.length) this._events[event] = null return this } // specific handler var cb var i = cbs.length while (i--) { cb = cbs[i] if (cb === fn || cb.fn === fn) { modifyListenerCount(this, event, -1) cbs.splice(i, 1) break } } return this } /** * Trigger an event on self. * * @param {String} event */ exports.$emit = function (event) { this._eventCancelled = false var cbs = this._events[event] if (cbs) { // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length - 1 var args = new Array(i) while (i--) { args[i] = arguments[i + 1] } i = 0 cbs = cbs.length > 1 ? _.toArray(cbs) : cbs for (var l = cbs.length; i < l; i++) { if (cbs[i].apply(this, args) === false) { this._eventCancelled = true } } } return this } /** * Recursively broadcast an event to all children instances. * * @param {String} event * @param {...*} additional arguments */ exports.$broadcast = function (event) { // if no child has registered for this event, // then there's no need to broadcast. if (!this._eventsCount[event]) return var children = this._children for (var i = 0, l = children.length; i < l; i++) { var child = children[i] child.$emit.apply(child, arguments) if (!child._eventCancelled) { child.$broadcast.apply(child, arguments) } } return this } /** * Recursively propagate an event up the parent chain. * * @param {String} event * @param {...*} additional arguments */ exports.$dispatch = function () { var parent = this.$parent while (parent) { parent.$emit.apply(parent, arguments) parent = parent._eventCancelled ? null : parent.$parent } return this } /** * Modify the listener counts on all parents. * This bookkeeping allows $broadcast to return early when * no child has listened to a certain event. * * @param {Vue} vm * @param {String} event * @param {Number} count */ var hookRE = /^hook:/ function modifyListenerCount (vm, event, count) { var parent = vm.$parent // hooks do not get broadcasted so no need // to do bookkeeping for them if (!parent || !count || hookRE.test(event)) return while (parent) { parent._eventsCount[event] = (parent._eventsCount[event] || 0) + count parent = parent.$parent } } /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Create a child instance that prototypally inehrits * data on parent. To achieve that we create an intermediate * constructor with its prototype pointing to parent. * * @param {Object} opts * @param {Function} [BaseCtor] * @return {Vue} * @public */ exports.$addChild = function (opts, BaseCtor) { BaseCtor = BaseCtor || _.Vue opts = opts || {} var parent = this var ChildVue var inherit = opts.inherit !== undefined ? opts.inherit : BaseCtor.options.inherit if (inherit) { var ctors = parent._childCtors ChildVue = ctors[BaseCtor.cid] if (!ChildVue) { var optionName = BaseCtor.options.name var className = optionName ? _.classify(optionName) : 'VueComponent' ChildVue = new Function( 'return function ' + className + ' (options) {' + 'this.constructor = ' + className + ';' + 'this._init(options) }' )() ChildVue.options = BaseCtor.options ChildVue.linker = BaseCtor.linker ChildVue.prototype = this ctors[BaseCtor.cid] = ChildVue } } else { ChildVue = BaseCtor } opts._parent = parent opts._root = parent.$root var child = new ChildVue(opts) return child } /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var compiler = __webpack_require__(10) /** * Set instance target element and kick off the compilation * process. The passed in `el` can be a selector string, an * existing Element, or a DocumentFragment (for block * instances). * * @param {Element|DocumentFragment|string} el * @public */ exports.$mount = function (el) { if (this._isCompiled) { _.warn('$mount() should be called only once.') return } if (!el) { el = document.createElement('div') } else if (typeof el === 'string') { var selector = el el = document.querySelector(el) if (!el) { _.warn('Cannot find element: ' + selector) return } } this._compile(el) this._isCompiled = true this._callHook('compiled') if (_.inDoc(this.$el)) { this._callHook('attached') this._initDOMHooks() ready.call(this) } else { this._initDOMHooks() this.$once('hook:attached', ready) } return this } /** * Mark an instance as ready. */ function ready () { this._isAttached = true this._isReady = true this._callHook('ready') } /** * Teardown the instance, simply delegate to the internal * _destroy. */ exports.$destroy = function (remove, deferCleanup) { this._destroy(remove, deferCleanup) } /** * Partially compile a piece of DOM and return a * decompile function. * * @param {Element|DocumentFragment} el * @param {Vue} [host] * @return {Function} */ exports.$compile = function (el, host) { return compiler.compile(el, this.$options, true, host)(this, el) } /***/ } /******/ ]) }); ;
test/components/label-spec.js
nordsoftware/react-foundation
import React from 'react'; import { render } from 'enzyme'; import { expect } from 'chai'; import { Label } from '../../src/components/label'; import { Colors } from '../../src/enums'; // TODO: Add test cases for invalid enum values describe('Label component', () => { it('sets tag name', () => { const component = render(<Label/>); expect(component).to.have.tagName('span'); }); it('sets default class name', () => { const component = render(<Label/>); expect(component).to.have.className('label'); }); it('does not set default class name', () => { const component = render(<Label noDefaultClassName/>); expect(component).to.not.have.className('label'); }); it('sets custom class name', () => { const component = render(<Label className="my-label"/>); expect(component).to.have.className('my-label'); }); it('sets color', () => { const component = render(<Label color={Colors.SUCCESS}/>); expect(component).to.have.className('success'); expect(component).to.not.have.attr('color'); }); it('sets contents', () => { const component = render(<Label>Build passing</Label>); expect(component).to.have.text('Build passing'); }); });
spec/components/snackbar.js
jasonleibowitz/react-toolbox
import React from 'react'; import Button from '../../components/button'; import Snackbar from '../../components/snackbar'; class SnackbarTest extends React.Component { state = { active: false }; handleSnackbarClick = () => { this.setState({active: false}); }; handleSnackbarTimeout = () => { this.setState({active: false}); }; handleClick = () => { this.setState({active: true}); }; render () { return ( <section> <h5>Snackbars & Toasts</h5> <p>lorem ipsum...</p> <Button label='Show snackbar' primary raised onClick={this.handleClick} /> <Snackbar action='Hide' active={this.state.active} timeout={2000} onClick={this.handleSnackbarClick} onTimeout={this.handleSnackbarTimeout} type='warning' > Snackbar action <strong>cancel</strong> </Snackbar> </section> ); } } export default SnackbarTest;
frontend/capitolwords-spa/src/components/Avatar/Avatar.story.js
sunlightlabs/Capitol-Words
import React from 'react'; import { storiesOf } from '@storybook/react'; import g from 'glamorous'; import Avatar from './Avatar'; const people = [ { "url": "https://www.congress.gov/member/raja-krishnamoorthi/K000391", "imageUrl": "https://theunitedstates.io/images/congress/225x275/K000391.jpg", "party": "Democrat" }, { "url": "https://www.congress.gov/member/david-young/Y000066", "imageUrl": "https://theunitedstates.io/images/congress/225x275/Y000066.jpg", "party": "Republican" }, { "url": "https://www.congress.gov/member/bernard-sanders/S000033", "imageUrl": "https://theunitedstates.io/images/congress/225x275/S000033.jpg", "party": "Independent" }, { "url": "https://www.congress.gov/member/tim-kaine/K000384", "imageUrl": "https://theunitedstates.io/images/congress/225x275/K000384.jpg", "party": "Democrat" }, { "url": "https://www.congress.gov/member/jared-huffman/H001068", "imageUrl": "https://theunitedstates.io/images/congress/225x275/H001068.jpg", "party": "Democrat" }, { "url": "https://www.congress.gov/member/madeleine-z.-bordallo/B001245", "imageUrl": "https://theunitedstates.io/images/congress/225x275/B001245.jpg", "party": "Democrat" }, { "url": "https://www.congress.gov/member/mark-pocan/P000607", "imageUrl": "https://theunitedstates.io/images/congress/225x275/P000607.jpg", "party": "Democrat" }, { "url": "https://www.congress.gov/member/bennie-g.-thompson/T000193", "imageUrl": "https://theunitedstates.io/images/congress/225x275/T000193.jpg", "party": "Democrat" }, { "url": "https://www.congress.gov/member/cathy-mcmorris-rodgers/M001159", "imageUrl": "https://theunitedstates.io/images/congress/225x275/M001159.jpg", "party": "Republican" } ]; storiesOf('Avatar', module) .add('Democrat', () => ( <Avatar person={people[0]} /> )) .add('Republican', () => ( <Avatar person={people[1]} /> )) .add('Independent', () => ( <Avatar person={people[2]} /> )) .add('Large size', () => ( <Avatar person={people[3]} size="large" /> ));
src/components/common/svg-icons/av/branding-watermark.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvBrandingWatermark = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16h-9v-6h9v6z"/> </SvgIcon> ); AvBrandingWatermark = pure(AvBrandingWatermark); AvBrandingWatermark.displayName = 'AvBrandingWatermark'; AvBrandingWatermark.muiName = 'SvgIcon'; export default AvBrandingWatermark;
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js
arbas/react-router
import React from 'react'; class Assignments extends React.Component { render () { return ( <div> <h3>Assignments</h3> {this.props.children || <p>Choose an assignment from the sidebar.</p>} </div> ); } } export default Assignments;
ajax/libs/react-dom/18.0.0-alpha-1a3f1afbd/umd/react-dom-server.browser.development.js
cdnjs/cdnjs
/** @license React vundefined * react-dom-server.browser.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, factory(global.ReactDOMServer = {}, global.React)); }(this, (function (exports, React) { 'use strict'; // Do not require this module directly! Use normal `invariant` calls with // template literal strings. The messages will be replaced with error codes // during build. function formatProdErrorMessage(code) { var url = 'https://reactjs.org/docs/error-decoder.html?invariant=' + code; for (var i = 1; i < arguments.length; i++) { url += '&args[]=' + encodeURIComponent(arguments[i]); } return "Minified React error #" + code + "; visit " + url + " for the full message or " + 'use the non-minified dev environment for full errors and additional ' + 'helpful warnings.'; } var ReactVersion = '18.0.0-1a3f1afbd'; var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } function error(format) { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var _assign = ReactInternals.assign; var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; var REACT_FRAGMENT_TYPE = 0xeacb; var REACT_STRICT_MODE_TYPE = 0xeacc; var REACT_PROFILER_TYPE = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; var REACT_SUSPENSE_TYPE = 0xead1; var REACT_SUSPENSE_LIST_TYPE = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; var REACT_CACHE_TYPE = 0xeae4; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); REACT_FRAGMENT_TYPE = symbolFor('react.fragment'); REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); REACT_PROFILER_TYPE = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); REACT_CACHE_TYPE = symbolFor('react.cache'); } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; case REACT_CACHE_TYPE: return 'Cache'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } } } return null; } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableSuspenseServerRenderer = true; // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: _assign({}, props, { value: prevLog }), info: _assign({}, props, { value: prevInfo }), warn: _assign({}, props, { value: prevWarn }), error: _assign({}, props, { value: prevError }), group: _assign({}, props, { value: prevGroup }), groupCollapsed: _assign({}, props, { value: prevGroupCollapsed }), groupEnd: _assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } var hasOwnProperty = Object.prototype.hasOwnProperty; var loggedTypeFailures = {}; var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var didWarnAboutInvalidateContextType; { didWarnAboutInvalidateContextType = new Set(); } var emptyObject = {}; { Object.freeze(emptyObject); } function maskContext(type, context) { var contextTypes = type.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; } function checkContextTypes(typeSpecs, values, location) { { checkPropTypes(typeSpecs, values, location, 'Component'); } } function validateContextBounds(context, threadID) { // If we don't have enough slots in this context to store this threadID, // fill it in without leaving any holes to ensure that the VM optimizes // this as non-holey index properties. // (Note: If `react` package is < 16.6, _threadCount is undefined.) for (var i = context._threadCount | 0; i <= threadID; i++) { // We assume that this is the same as the defaultValue which might not be // true if we're rendering inside a secondary renderer but they are // secondary because these use cases are very rare. context[i] = context._currentValue2; context._threadCount = i + 1; } } function processContext(type, context, threadID, isClass) { if (isClass) { var contextType = type.contextType; { if ('contextType' in type) { var isValid = // Allow null for conditional declaration contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer> if (!isValid && !didWarnAboutInvalidateContextType.has(type)) { didWarnAboutInvalidateContextType.add(type); var addendum = ''; if (contextType === undefined) { addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; } else if (typeof contextType !== 'object') { addendum = ' However, it is set to a ' + typeof contextType + '.'; } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { addendum = ' Did you accidentally pass the Context.Provider instead?'; } else if (contextType._context !== undefined) { // <Context.Consumer> addendum = ' Did you accidentally pass the Context.Consumer instead?'; } else { addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; } error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(type) || 'Component', addendum); } } } if (typeof contextType === 'object' && contextType !== null) { validateContextBounds(contextType, threadID); return contextType[threadID]; } { var maskedContext = maskContext(type, context); { if (type.contextTypes) { checkContextTypes(type.contextTypes, maskedContext, 'context'); } } return maskedContext; } } else { { var _maskedContext = maskContext(type, context); { if (type.contextTypes) { checkContextTypes(type.contextTypes, _maskedContext, 'context'); } } return _maskedContext; } } } var nextAvailableThreadIDs = new Uint16Array(16); for (var i = 0; i < 15; i++) { nextAvailableThreadIDs[i] = i + 1; } nextAvailableThreadIDs[15] = 0; function growThreadCountAndReturnNextAvailable() { var oldArray = nextAvailableThreadIDs; var oldSize = oldArray.length; var newSize = oldSize * 2; if (!(newSize <= 0x10000)) { { throw Error( "Maximum number of concurrent React renderers exceeded. This can happen if you are not properly destroying the Readable provided by React. Ensure that you call .destroy() on it if you no longer want to read from it, and did not read to the end. If you use .pipe() this should be automatic." ); } } var newArray = new Uint16Array(newSize); newArray.set(oldArray); nextAvailableThreadIDs = newArray; nextAvailableThreadIDs[0] = oldSize + 1; for (var _i = oldSize; _i < newSize - 1; _i++) { nextAvailableThreadIDs[_i] = _i + 1; } nextAvailableThreadIDs[newSize - 1] = 0; return oldSize; } function allocThreadID() { var nextID = nextAvailableThreadIDs[0]; if (nextID === 0) { return growThreadCountAndReturnNextAvailable(); } nextAvailableThreadIDs[0] = nextAvailableThreadIDs[nextID]; return nextID; } function freeThreadID(id) { nextAvailableThreadIDs[id] = nextAvailableThreadIDs[0]; nextAvailableThreadIDs[0] = id; } // A reserved attribute. // It is handled by React separately and shouldn't be written to the DOM. var RESERVED = 0; // A simple string attribute. // Attributes that aren't in the filter are presumed to have this type. var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called // "enumerated" attributes with "true" and "false" as possible values. // When true, it should be set to a "true" string. // When false, it should be set to a "false" string. var BOOLEANISH_STRING = 2; // A real boolean attribute. // When true, it should be present (set either to an empty string or its name). // When false, it should be omitted. var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. // When true, it should be present (set either to an empty string or its name). // When false, it should be omitted. // For any other value, should be present with that value. var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. // When falsy, it should be removed. var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. // When falsy, it should be removed. var POSITIVE_NUMERIC = 6; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; /* eslint-enable max-len */ var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { return true; } if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; { error('Invalid attribute name: `%s`', attributeName); } return false; } function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null) { return propertyInfo.type === RESERVED; } if (isCustomComponentTag) { return false; } if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { return true; } return false; } function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null && propertyInfo.type === RESERVED) { return false; } switch (typeof value) { case 'function': // $FlowIssue symbol is perfectly valid here case 'symbol': // eslint-disable-line return true; case 'boolean': { if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { return !propertyInfo.acceptsBooleans; } else { var prefix = name.toLowerCase().slice(0, 5); return prefix !== 'data-' && prefix !== 'aria-'; } } default: return false; } } function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { if (value === null || typeof value === 'undefined') { return true; } if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { return true; } if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { switch (propertyInfo.type) { case BOOLEAN: return !value; case OVERLOADED_BOOLEAN: return value === false; case NUMERIC: return isNaN(value); case POSITIVE_NUMERIC: return isNaN(value) || value < 1; } } return false; } function getPropertyInfo(name) { return properties.hasOwnProperty(name) ? properties[name] : null; } function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; this.attributeName = attributeName; this.attributeNamespace = attributeNamespace; this.mustUseProperty = mustUseProperty; this.propertyName = name; this.type = type; this.sanitizeURL = sanitizeURL; this.removeEmptyString = removeEmptyString; } // When adding attributes to this list, be sure to also add them to // the `possibleStandardNames` module to ensure casing and incorrect // name warnings. var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular // elements (not just inputs). Now that ReactDOMInput assigns to the // defaultValue property -- do we need this? 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; reservedProps.forEach(function (name) { properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // A few React string attributes have a different name. // This is a mapping from React prop names to the attribute names. [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { var name = _ref[0], attributeName = _ref[1]; properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are "enumerated" HTML attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically // these aren't boolean attributes (they are coerced to strings). ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are "enumerated" SVG attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically // these aren't boolean attributes (they are coerced to strings). // Since these are SVG attributes, their attribute names are case-sensitive. ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML boolean attributes. ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM // on the client side because the browsers are inconsistent. Instead we call focus(). 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata 'itemScope'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are the few React props that we set as DOM properties // rather than attributes. These are all booleans. ['checked', // Note: `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. We have special logic for handling this. 'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that are "overloaded booleans": they behave like // booleans, but can also accept a string value. ['capture', 'download' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that must be positive numbers. ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that must be numbers. ['rowSpan', 'start'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); var CAMELIZE = /[\-\:]([a-z])/g; var capitalize = function (token) { return token[1].toUpperCase(); }; // This is a list of all SVG attributes that need special casing, namespacing, // or boolean value assignment. Regular attributes that just accept strings // and have the same names are omitted, just like in the HTML attribute filter. // Some of these attributes can be hard to find. This list was created by // scraping the MDN documentation. ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, null, // attributeNamespace false, // sanitizeURL false); }); // String SVG attributes with the xlink namespace. ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL false); }); // String SVG attributes with the xml namespace. ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL false); }); // These attribute exists both in HTML and SVG. // The attribute name is case-sensitive in SVG so we can't just use // the React name like we do for attributes that exist only in HTML. ['tabIndex', 'crossOrigin'].forEach(function (attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These attributes accept URLs. These must not allow javascript: URLS. // These will also need to accept Trusted Types object in the future. var xlinkHref = 'xlinkHref'; properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty 'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL false); ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace true, // sanitizeURL true); }); // and any newline or tab are filtered out as if they're not part of the URL. // https://url.spec.whatwg.org/#url-parsing // Tab or newline are defined as \r\n\t: // https://infra.spec.whatwg.org/#ascii-tab-or-newline // A C0 control is a code point in the range \u0000 NULL to \u001F // INFORMATION SEPARATOR ONE, inclusive: // https://infra.spec.whatwg.org/#c0-control-or-space /* eslint-disable max-len */ var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; var didWarn = false; function sanitizeURL(url) { { if (!didWarn && isJavaScriptProtocol.test(url)) { didWarn = true; error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); } } } // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escapes special characters and HTML entities in a given html string. * * @param {string} string HTML string to escape for later insertion * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextForBrowser(value) + '"'; } /** * Operations for dealing with DOM properties. */ /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ function createMarkupForProperty(name, value) { var propertyInfo = getPropertyInfo(name); if (name !== 'style' && shouldIgnoreAttribute(name, propertyInfo, false)) { return ''; } if (shouldRemoveAttribute(name, value, propertyInfo, false)) { return ''; } if (propertyInfo !== null) { var attributeName = propertyInfo.attributeName; var type = propertyInfo.type; if (type === BOOLEAN || type === OVERLOADED_BOOLEAN && value === true) { return attributeName + '=""'; } else { if (propertyInfo.sanitizeURL) { value = '' + value; sanitizeURL(value); } return attributeName + '=' + quoteAttributeValueForBrowser(value); } } else if (isAttributeNameSafe(name)) { return name + '=' + quoteAttributeValueForBrowser(value); } return ''; } /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ function createMarkupForCustomAttribute(name, value) { if (!isAttributeNameSafe(name) || value == null || typeof value === 'function' || typeof value === 'symbol') { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare ; } var objectIs = typeof Object.is === 'function' ? Object.is : is; var currentlyRenderingComponent = null; var firstWorkInProgressHook = null; var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook var isReRender = false; // Whether an update was scheduled during the currently executing render pass. var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates var renderPhaseUpdates = null; // Counter to prevent infinite loops. var numberOfReRenders = 0; var RE_RENDER_LIMIT = 25; var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook var currentHookNameInDev; function resolveCurrentlyRenderingComponent() { if (!(currentlyRenderingComponent !== null)) { { throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." ); } } { if (isInHookUserCodeInDev) { error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); } } return currentlyRenderingComponent; } function areHookInputsEqual(nextDeps, prevDeps) { if (prevDeps === null) { { error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); } return false; } { // Don't bother comparing lengths in prod because these arrays should be // passed inline. if (nextDeps.length !== prevDeps.length) { error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]"); } } for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { if (objectIs(nextDeps[i], prevDeps[i])) { continue; } return false; } return true; } function createHook() { if (numberOfReRenders > 0) { { { throw Error( "Rendered more hooks than during the previous render" ); } } } return { memoizedState: null, queue: null, next: null }; } function createWorkInProgressHook() { if (workInProgressHook === null) { // This is the first hook in the list if (firstWorkInProgressHook === null) { isReRender = false; firstWorkInProgressHook = workInProgressHook = createHook(); } else { // There's already a work-in-progress. Reuse it. isReRender = true; workInProgressHook = firstWorkInProgressHook; } } else { if (workInProgressHook.next === null) { isReRender = false; // Append to the end of the list workInProgressHook = workInProgressHook.next = createHook(); } else { // There's already a work-in-progress. Reuse it. isReRender = true; workInProgressHook = workInProgressHook.next; } } return workInProgressHook; } function prepareToUseHooks(componentIdentity) { currentlyRenderingComponent = componentIdentity; { isInHookUserCodeInDev = false; } // The following should have already been reset // didScheduleRenderPhaseUpdate = false; // firstWorkInProgressHook = null; // numberOfReRenders = 0; // renderPhaseUpdates = null; // workInProgressHook = null; } function finishHooks(Component, props, children, refOrContext) { // This must be called after every function component to prevent hooks from // being used in classes. while (didScheduleRenderPhaseUpdate) { // Updates were scheduled during the render phase. They are stored in // the `renderPhaseUpdates` map. Call the component again, reusing the // work-in-progress hooks and applying the additional updates on top. Keep // restarting until no more updates are scheduled. didScheduleRenderPhaseUpdate = false; numberOfReRenders += 1; // Start over from the beginning of the list workInProgressHook = null; children = Component(props, refOrContext); } resetHooksState(); return children; } // Reset the internal hooks state if an error occurs while rendering a component function resetHooksState() { { isInHookUserCodeInDev = false; } currentlyRenderingComponent = null; didScheduleRenderPhaseUpdate = false; firstWorkInProgressHook = null; numberOfReRenders = 0; renderPhaseUpdates = null; workInProgressHook = null; } function readContext(context) { var threadID = currentPartialRenderer.threadID; validateContextBounds(context, threadID); { if (isInHookUserCodeInDev) { error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); } } return context[threadID]; } function useContext(context) { { currentHookNameInDev = 'useContext'; } resolveCurrentlyRenderingComponent(); var threadID = currentPartialRenderer.threadID; validateContextBounds(context, threadID); return context[threadID]; } function basicStateReducer(state, action) { // $FlowFixMe: Flow doesn't like mixed types return typeof action === 'function' ? action(state) : action; } function useState(initialState) { { currentHookNameInDev = 'useState'; } return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers initialState); } function useReducer(reducer, initialArg, init) { { if (reducer !== basicStateReducer) { currentHookNameInDev = 'useReducer'; } } currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); workInProgressHook = createWorkInProgressHook(); if (isReRender) { // This is a re-render. Apply the new render phase updates to the previous // current hook. var queue = workInProgressHook.queue; var dispatch = queue.dispatch; if (renderPhaseUpdates !== null) { // Render phase updates are stored in a map of queue -> linked list var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); if (firstRenderPhaseUpdate !== undefined) { renderPhaseUpdates.delete(queue); var newState = workInProgressHook.memoizedState; var update = firstRenderPhaseUpdate; do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. var action = update.action; { isInHookUserCodeInDev = true; } newState = reducer(newState, action); { isInHookUserCodeInDev = false; } update = update.next; } while (update !== null); workInProgressHook.memoizedState = newState; return [newState, dispatch]; } } return [workInProgressHook.memoizedState, dispatch]; } else { { isInHookUserCodeInDev = true; } var initialState; if (reducer === basicStateReducer) { // Special case for `useState`. initialState = typeof initialArg === 'function' ? initialArg() : initialArg; } else { initialState = init !== undefined ? init(initialArg) : initialArg; } { isInHookUserCodeInDev = false; } workInProgressHook.memoizedState = initialState; var _queue = workInProgressHook.queue = { last: null, dispatch: null }; var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue); return [workInProgressHook.memoizedState, _dispatch]; } } function useMemo(nextCreate, deps) { currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); workInProgressHook = createWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; if (workInProgressHook !== null) { var prevState = workInProgressHook.memoizedState; if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } } { isInHookUserCodeInDev = true; } var nextValue = nextCreate(); { isInHookUserCodeInDev = false; } workInProgressHook.memoizedState = [nextValue, nextDeps]; return nextValue; } function useRef(initialValue) { currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); workInProgressHook = createWorkInProgressHook(); var previousRef = workInProgressHook.memoizedState; if (previousRef === null) { var ref = { current: initialValue }; { Object.seal(ref); } workInProgressHook.memoizedState = ref; return ref; } else { return previousRef; } } function useLayoutEffect(create, inputs) { { currentHookNameInDev = 'useLayoutEffect'; error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.'); } } function dispatchAction(componentIdentity, queue, action) { if (!(numberOfReRenders < RE_RENDER_LIMIT)) { { throw Error( "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); } } if (componentIdentity === currentlyRenderingComponent) { // This is a render phase update. Stash it in a lazily-created map of // queue -> linked list of updates. After this render pass, we'll restart // and apply the stashed updates on top of the work-in-progress hook. didScheduleRenderPhaseUpdate = true; var update = { action: action, next: null }; if (renderPhaseUpdates === null) { renderPhaseUpdates = new Map(); } var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); if (firstRenderPhaseUpdate === undefined) { renderPhaseUpdates.set(queue, update); } else { // Append the update to the end of the list. var lastRenderPhaseUpdate = firstRenderPhaseUpdate; while (lastRenderPhaseUpdate.next !== null) { lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; } lastRenderPhaseUpdate.next = update; } } } function useCallback(callback, deps) { return useMemo(function () { return callback; }, deps); } // TODO Decide on how to implement this hook for server rendering. // If a mutation occurs during render, consider triggering a Suspense boundary // and falling back to client rendering. function useMutableSource(source, getSnapshot, subscribe) { resolveCurrentlyRenderingComponent(); return getSnapshot(source._source); } function useDeferredValue(value) { resolveCurrentlyRenderingComponent(); return value; } function useTransition() { resolveCurrentlyRenderingComponent(); var startTransition = function (callback) { callback(); }; return [false, startTransition]; } function useOpaqueIdentifier() { return (currentPartialRenderer.identifierPrefix || '') + 'R:' + (currentPartialRenderer.uniqueID++).toString(36); } function noop() {} var currentPartialRenderer = null; function setCurrentPartialRenderer(renderer) { currentPartialRenderer = renderer; } var Dispatcher = { readContext: readContext, useContext: useContext, useMemo: useMemo, useReducer: useReducer, useRef: useRef, useState: useState, useLayoutEffect: useLayoutEffect, useCallback: useCallback, // useImperativeHandle is not run in the server environment useImperativeHandle: noop, // Effects are not run in the server environment. useEffect: noop, // Debugging effect useDebugValue: noop, useDeferredValue: useDeferredValue, useTransition: useTransition, useOpaqueIdentifier: useOpaqueIdentifier, // Subscriptions are not setup in a server environment. useMutableSource: useMutableSource }; var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Assumes there is no parent namespace. function getIntrinsicNamespace(type) { switch (type) { case 'svg': return SVG_NAMESPACE; case 'math': return MATH_NAMESPACE; default: return HTML_NAMESPACE; } } function getChildNamespace(parentNamespace, type) { if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) { // No (or default) parent namespace: potential entry point. return getIntrinsicNamespace(type); } if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') { // We're leaving SVG. return HTML_NAMESPACE; } // By default, pass namespace below. return parentNamespace; } var hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true }; function checkControlledValueProps(tagName, props) { { if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { 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`.'); } if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { 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`.'); } } } // For HTML, certain tags should omit their close tag. We keep a list for // those special-case tags. var omittedCloseTags = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems. }; // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ menuitem: true }, omittedCloseTags); var HTML = '__html'; function assertValidProps(tag, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[tag]) { if (!(props.children == null && props.dangerouslySetInnerHTML == null)) { { throw Error( tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." ); } } } if (props.dangerouslySetInnerHTML != null) { if (!(props.children == null)) { { throw Error( "Can only set one of `children` or `props.dangerouslySetInnerHTML`." ); } } if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML)) { { throw Error( "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information." ); } } } { if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) { error('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.'); } } if (!(props.style == null || typeof props.style === 'object')) { { throw Error( "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." ); } } } /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, aspectRatio: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, columns: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridArea: true, gridRow: true, gridRowEnd: true, gridRowSpan: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnSpan: true, gridColumnStart: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, isCustomProperty) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) { return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers } return ('' + value).trim(); } var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. */ function hyphenateStyleName(name) { return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } function isCustomComponent(tagName, props) { if (tagName.indexOf('-') === -1) { return typeof props.is === 'string'; } switch (tagName) { // These are reserved SVG and MathML elements. // We don't mind this list too much because we expect it to never grow. // The alternative is to track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': case 'color-profile': case 'font-face': case 'font-face-src': case 'font-face-uri': case 'font-face-format': case 'font-face-name': case 'missing-glyph': return false; default: return true; } } var warnValidStyle = function () {}; { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; var msPattern$1 = /^-ms-/; var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnedForInfinityValue = false; var camelize = function (string) { return string.replace(hyphenPattern, function (_, character) { return character.toUpperCase(); }); }; var warnHyphenatedStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix // is converted to lowercase `ms`. camelize(name.replace(msPattern$1, 'ms-'))); }; var warnBadVendoredStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)); }; var warnStyleValueWithSemicolon = function (name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')); }; var warnStyleValueIsNaN = function (name, value) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; error('`NaN` is an invalid value for the `%s` css style property.', name); }; var warnStyleValueIsInfinity = function (name, value) { if (warnedForInfinityValue) { return; } warnedForInfinityValue = true; error('`Infinity` is an invalid value for the `%s` css style property.', name); }; warnValidStyle = function (name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } if (typeof value === 'number') { if (isNaN(value)) { warnStyleValueIsNaN(name, value); } else if (!isFinite(value)) { warnStyleValueIsInfinity(name, value); } } }; } var warnValidStyle$1 = warnValidStyle; var ariaProperties = { 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }; var warnedProperties = {}; var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); function validateProperty(tagName, name) { { if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { return true; } if (rARIACamel.test(name)) { var ariaName = 'aria-' + name.slice(4).toLowerCase(); var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (correctName == null) { error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name); warnedProperties[name] = true; return true; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== correctName) { error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName); warnedProperties[name] = true; return true; } } if (rARIA.test(name)) { var lowerCasedName = name.toLowerCase(); var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (standardName == null) { warnedProperties[name] = true; return false; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== standardName) { error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName); warnedProperties[name] = true; return true; } } } return true; } function warnInvalidARIAProps(type, props) { { var invalidProps = []; for (var key in props) { var isValid = validateProperty(type, key); if (!isValid) { invalidProps.push(key); } } var unknownPropString = invalidProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (invalidProps.length === 1) { error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } else if (invalidProps.length > 1) { error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } } } function validateProperties(type, props) { if (isCustomComponent(type, props)) { return; } warnInvalidARIAProps(type, props); } var didWarnValueNull = false; function validateProperties$1(type, props) { { if (type !== 'input' && type !== 'textarea' && type !== 'select') { return; } if (props != null && props.value === null && !didWarnValueNull) { didWarnValueNull = true; if (type === 'select' && props.multiple) { error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type); } else { error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type); } } } } // When adding attributes to the HTML or SVG allowed attribute list, be sure to // also add them to this module to ensure casing and incorrect name // warnings. var possibleStandardNames = { // HTML accept: 'accept', acceptcharset: 'acceptCharset', 'accept-charset': 'acceptCharset', accesskey: 'accessKey', action: 'action', allowfullscreen: 'allowFullScreen', alt: 'alt', as: 'as', async: 'async', autocapitalize: 'autoCapitalize', autocomplete: 'autoComplete', autocorrect: 'autoCorrect', autofocus: 'autoFocus', autoplay: 'autoPlay', autosave: 'autoSave', capture: 'capture', cellpadding: 'cellPadding', cellspacing: 'cellSpacing', challenge: 'challenge', charset: 'charSet', checked: 'checked', children: 'children', cite: 'cite', class: 'className', classid: 'classID', classname: 'className', cols: 'cols', colspan: 'colSpan', content: 'content', contenteditable: 'contentEditable', contextmenu: 'contextMenu', controls: 'controls', controlslist: 'controlsList', coords: 'coords', crossorigin: 'crossOrigin', dangerouslysetinnerhtml: 'dangerouslySetInnerHTML', data: 'data', datetime: 'dateTime', default: 'default', defaultchecked: 'defaultChecked', defaultvalue: 'defaultValue', defer: 'defer', dir: 'dir', disabled: 'disabled', disablepictureinpicture: 'disablePictureInPicture', disableremoteplayback: 'disableRemotePlayback', download: 'download', draggable: 'draggable', enctype: 'encType', enterkeyhint: 'enterKeyHint', for: 'htmlFor', form: 'form', formmethod: 'formMethod', formaction: 'formAction', formenctype: 'formEncType', formnovalidate: 'formNoValidate', formtarget: 'formTarget', frameborder: 'frameBorder', headers: 'headers', height: 'height', hidden: 'hidden', high: 'high', href: 'href', hreflang: 'hrefLang', htmlfor: 'htmlFor', httpequiv: 'httpEquiv', 'http-equiv': 'httpEquiv', icon: 'icon', id: 'id', innerhtml: 'innerHTML', inputmode: 'inputMode', integrity: 'integrity', is: 'is', itemid: 'itemID', itemprop: 'itemProp', itemref: 'itemRef', itemscope: 'itemScope', itemtype: 'itemType', keyparams: 'keyParams', keytype: 'keyType', kind: 'kind', label: 'label', lang: 'lang', list: 'list', loop: 'loop', low: 'low', manifest: 'manifest', marginwidth: 'marginWidth', marginheight: 'marginHeight', max: 'max', maxlength: 'maxLength', media: 'media', mediagroup: 'mediaGroup', method: 'method', min: 'min', minlength: 'minLength', multiple: 'multiple', muted: 'muted', name: 'name', nomodule: 'noModule', nonce: 'nonce', novalidate: 'noValidate', open: 'open', optimum: 'optimum', pattern: 'pattern', placeholder: 'placeholder', playsinline: 'playsInline', poster: 'poster', preload: 'preload', profile: 'profile', radiogroup: 'radioGroup', readonly: 'readOnly', referrerpolicy: 'referrerPolicy', rel: 'rel', required: 'required', reversed: 'reversed', role: 'role', rows: 'rows', rowspan: 'rowSpan', sandbox: 'sandbox', scope: 'scope', scoped: 'scoped', scrolling: 'scrolling', seamless: 'seamless', selected: 'selected', shape: 'shape', size: 'size', sizes: 'sizes', span: 'span', spellcheck: 'spellCheck', src: 'src', srcdoc: 'srcDoc', srclang: 'srcLang', srcset: 'srcSet', start: 'start', step: 'step', style: 'style', summary: 'summary', tabindex: 'tabIndex', target: 'target', title: 'title', type: 'type', usemap: 'useMap', value: 'value', width: 'width', wmode: 'wmode', wrap: 'wrap', // SVG about: 'about', accentheight: 'accentHeight', 'accent-height': 'accentHeight', accumulate: 'accumulate', additive: 'additive', alignmentbaseline: 'alignmentBaseline', 'alignment-baseline': 'alignmentBaseline', allowreorder: 'allowReorder', alphabetic: 'alphabetic', amplitude: 'amplitude', arabicform: 'arabicForm', 'arabic-form': 'arabicForm', ascent: 'ascent', attributename: 'attributeName', attributetype: 'attributeType', autoreverse: 'autoReverse', azimuth: 'azimuth', basefrequency: 'baseFrequency', baselineshift: 'baselineShift', 'baseline-shift': 'baselineShift', baseprofile: 'baseProfile', bbox: 'bbox', begin: 'begin', bias: 'bias', by: 'by', calcmode: 'calcMode', capheight: 'capHeight', 'cap-height': 'capHeight', clip: 'clip', clippath: 'clipPath', 'clip-path': 'clipPath', clippathunits: 'clipPathUnits', cliprule: 'clipRule', 'clip-rule': 'clipRule', color: 'color', colorinterpolation: 'colorInterpolation', 'color-interpolation': 'colorInterpolation', colorinterpolationfilters: 'colorInterpolationFilters', 'color-interpolation-filters': 'colorInterpolationFilters', colorprofile: 'colorProfile', 'color-profile': 'colorProfile', colorrendering: 'colorRendering', 'color-rendering': 'colorRendering', contentscripttype: 'contentScriptType', contentstyletype: 'contentStyleType', cursor: 'cursor', cx: 'cx', cy: 'cy', d: 'd', datatype: 'datatype', decelerate: 'decelerate', descent: 'descent', diffuseconstant: 'diffuseConstant', direction: 'direction', display: 'display', divisor: 'divisor', dominantbaseline: 'dominantBaseline', 'dominant-baseline': 'dominantBaseline', dur: 'dur', dx: 'dx', dy: 'dy', edgemode: 'edgeMode', elevation: 'elevation', enablebackground: 'enableBackground', 'enable-background': 'enableBackground', end: 'end', exponent: 'exponent', externalresourcesrequired: 'externalResourcesRequired', fill: 'fill', fillopacity: 'fillOpacity', 'fill-opacity': 'fillOpacity', fillrule: 'fillRule', 'fill-rule': 'fillRule', filter: 'filter', filterres: 'filterRes', filterunits: 'filterUnits', floodopacity: 'floodOpacity', 'flood-opacity': 'floodOpacity', floodcolor: 'floodColor', 'flood-color': 'floodColor', focusable: 'focusable', fontfamily: 'fontFamily', 'font-family': 'fontFamily', fontsize: 'fontSize', 'font-size': 'fontSize', fontsizeadjust: 'fontSizeAdjust', 'font-size-adjust': 'fontSizeAdjust', fontstretch: 'fontStretch', 'font-stretch': 'fontStretch', fontstyle: 'fontStyle', 'font-style': 'fontStyle', fontvariant: 'fontVariant', 'font-variant': 'fontVariant', fontweight: 'fontWeight', 'font-weight': 'fontWeight', format: 'format', from: 'from', fx: 'fx', fy: 'fy', g1: 'g1', g2: 'g2', glyphname: 'glyphName', 'glyph-name': 'glyphName', glyphorientationhorizontal: 'glyphOrientationHorizontal', 'glyph-orientation-horizontal': 'glyphOrientationHorizontal', glyphorientationvertical: 'glyphOrientationVertical', 'glyph-orientation-vertical': 'glyphOrientationVertical', glyphref: 'glyphRef', gradienttransform: 'gradientTransform', gradientunits: 'gradientUnits', hanging: 'hanging', horizadvx: 'horizAdvX', 'horiz-adv-x': 'horizAdvX', horizoriginx: 'horizOriginX', 'horiz-origin-x': 'horizOriginX', ideographic: 'ideographic', imagerendering: 'imageRendering', 'image-rendering': 'imageRendering', in2: 'in2', in: 'in', inlist: 'inlist', intercept: 'intercept', k1: 'k1', k2: 'k2', k3: 'k3', k4: 'k4', k: 'k', kernelmatrix: 'kernelMatrix', kernelunitlength: 'kernelUnitLength', kerning: 'kerning', keypoints: 'keyPoints', keysplines: 'keySplines', keytimes: 'keyTimes', lengthadjust: 'lengthAdjust', letterspacing: 'letterSpacing', 'letter-spacing': 'letterSpacing', lightingcolor: 'lightingColor', 'lighting-color': 'lightingColor', limitingconeangle: 'limitingConeAngle', local: 'local', markerend: 'markerEnd', 'marker-end': 'markerEnd', markerheight: 'markerHeight', markermid: 'markerMid', 'marker-mid': 'markerMid', markerstart: 'markerStart', 'marker-start': 'markerStart', markerunits: 'markerUnits', markerwidth: 'markerWidth', mask: 'mask', maskcontentunits: 'maskContentUnits', maskunits: 'maskUnits', mathematical: 'mathematical', mode: 'mode', numoctaves: 'numOctaves', offset: 'offset', opacity: 'opacity', operator: 'operator', order: 'order', orient: 'orient', orientation: 'orientation', origin: 'origin', overflow: 'overflow', overlineposition: 'overlinePosition', 'overline-position': 'overlinePosition', overlinethickness: 'overlineThickness', 'overline-thickness': 'overlineThickness', paintorder: 'paintOrder', 'paint-order': 'paintOrder', panose1: 'panose1', 'panose-1': 'panose1', pathlength: 'pathLength', patterncontentunits: 'patternContentUnits', patterntransform: 'patternTransform', patternunits: 'patternUnits', pointerevents: 'pointerEvents', 'pointer-events': 'pointerEvents', points: 'points', pointsatx: 'pointsAtX', pointsaty: 'pointsAtY', pointsatz: 'pointsAtZ', prefix: 'prefix', preservealpha: 'preserveAlpha', preserveaspectratio: 'preserveAspectRatio', primitiveunits: 'primitiveUnits', property: 'property', r: 'r', radius: 'radius', refx: 'refX', refy: 'refY', renderingintent: 'renderingIntent', 'rendering-intent': 'renderingIntent', repeatcount: 'repeatCount', repeatdur: 'repeatDur', requiredextensions: 'requiredExtensions', requiredfeatures: 'requiredFeatures', resource: 'resource', restart: 'restart', result: 'result', results: 'results', rotate: 'rotate', rx: 'rx', ry: 'ry', scale: 'scale', security: 'security', seed: 'seed', shaperendering: 'shapeRendering', 'shape-rendering': 'shapeRendering', slope: 'slope', spacing: 'spacing', specularconstant: 'specularConstant', specularexponent: 'specularExponent', speed: 'speed', spreadmethod: 'spreadMethod', startoffset: 'startOffset', stddeviation: 'stdDeviation', stemh: 'stemh', stemv: 'stemv', stitchtiles: 'stitchTiles', stopcolor: 'stopColor', 'stop-color': 'stopColor', stopopacity: 'stopOpacity', 'stop-opacity': 'stopOpacity', strikethroughposition: 'strikethroughPosition', 'strikethrough-position': 'strikethroughPosition', strikethroughthickness: 'strikethroughThickness', 'strikethrough-thickness': 'strikethroughThickness', string: 'string', stroke: 'stroke', strokedasharray: 'strokeDasharray', 'stroke-dasharray': 'strokeDasharray', strokedashoffset: 'strokeDashoffset', 'stroke-dashoffset': 'strokeDashoffset', strokelinecap: 'strokeLinecap', 'stroke-linecap': 'strokeLinecap', strokelinejoin: 'strokeLinejoin', 'stroke-linejoin': 'strokeLinejoin', strokemiterlimit: 'strokeMiterlimit', 'stroke-miterlimit': 'strokeMiterlimit', strokewidth: 'strokeWidth', 'stroke-width': 'strokeWidth', strokeopacity: 'strokeOpacity', 'stroke-opacity': 'strokeOpacity', suppresscontenteditablewarning: 'suppressContentEditableWarning', suppresshydrationwarning: 'suppressHydrationWarning', surfacescale: 'surfaceScale', systemlanguage: 'systemLanguage', tablevalues: 'tableValues', targetx: 'targetX', targety: 'targetY', textanchor: 'textAnchor', 'text-anchor': 'textAnchor', textdecoration: 'textDecoration', 'text-decoration': 'textDecoration', textlength: 'textLength', textrendering: 'textRendering', 'text-rendering': 'textRendering', to: 'to', transform: 'transform', typeof: 'typeof', u1: 'u1', u2: 'u2', underlineposition: 'underlinePosition', 'underline-position': 'underlinePosition', underlinethickness: 'underlineThickness', 'underline-thickness': 'underlineThickness', unicode: 'unicode', unicodebidi: 'unicodeBidi', 'unicode-bidi': 'unicodeBidi', unicoderange: 'unicodeRange', 'unicode-range': 'unicodeRange', unitsperem: 'unitsPerEm', 'units-per-em': 'unitsPerEm', unselectable: 'unselectable', valphabetic: 'vAlphabetic', 'v-alphabetic': 'vAlphabetic', values: 'values', vectoreffect: 'vectorEffect', 'vector-effect': 'vectorEffect', version: 'version', vertadvy: 'vertAdvY', 'vert-adv-y': 'vertAdvY', vertoriginx: 'vertOriginX', 'vert-origin-x': 'vertOriginX', vertoriginy: 'vertOriginY', 'vert-origin-y': 'vertOriginY', vhanging: 'vHanging', 'v-hanging': 'vHanging', videographic: 'vIdeographic', 'v-ideographic': 'vIdeographic', viewbox: 'viewBox', viewtarget: 'viewTarget', visibility: 'visibility', vmathematical: 'vMathematical', 'v-mathematical': 'vMathematical', vocab: 'vocab', widths: 'widths', wordspacing: 'wordSpacing', 'word-spacing': 'wordSpacing', writingmode: 'writingMode', 'writing-mode': 'writingMode', x1: 'x1', x2: 'x2', x: 'x', xchannelselector: 'xChannelSelector', xheight: 'xHeight', 'x-height': 'xHeight', xlinkactuate: 'xlinkActuate', 'xlink:actuate': 'xlinkActuate', xlinkarcrole: 'xlinkArcrole', 'xlink:arcrole': 'xlinkArcrole', xlinkhref: 'xlinkHref', 'xlink:href': 'xlinkHref', xlinkrole: 'xlinkRole', 'xlink:role': 'xlinkRole', xlinkshow: 'xlinkShow', 'xlink:show': 'xlinkShow', xlinktitle: 'xlinkTitle', 'xlink:title': 'xlinkTitle', xlinktype: 'xlinkType', 'xlink:type': 'xlinkType', xmlbase: 'xmlBase', 'xml:base': 'xmlBase', xmllang: 'xmlLang', 'xml:lang': 'xmlLang', xmlns: 'xmlns', 'xml:space': 'xmlSpace', xmlnsxlink: 'xmlnsXlink', 'xmlns:xlink': 'xmlnsXlink', xmlspace: 'xmlSpace', y1: 'y1', y2: 'y2', y: 'y', ychannelselector: 'yChannelSelector', z: 'z', zoomandpan: 'zoomAndPan' }; var validateProperty$1 = function () {}; { var warnedProperties$1 = {}; var EVENT_NAME_REGEX = /^on./; var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); validateProperty$1 = function (tagName, name, value, eventRegistry) { if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { return true; } var lowerCasedName = name.toLowerCase(); if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') { error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); warnedProperties$1[name] = true; return true; } // We can't rely on the event system being injected on the server. if (eventRegistry != null) { var registrationNameDependencies = eventRegistry.registrationNameDependencies, possibleRegistrationNames = eventRegistry.possibleRegistrationNames; if (registrationNameDependencies.hasOwnProperty(name)) { return true; } var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; if (registrationName != null) { error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName); warnedProperties$1[name] = true; return true; } if (EVENT_NAME_REGEX.test(name)) { error('Unknown event handler property `%s`. It will be ignored.', name); warnedProperties$1[name] = true; return true; } } else if (EVENT_NAME_REGEX.test(name)) { // If no event plugins have been injected, we are in a server environment. // So we can't tell if the event name is correct for sure, but we can filter // out known bad ones like `onclick`. We can't suggest a specific replacement though. if (INVALID_EVENT_NAME_REGEX.test(name)) { error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name); } warnedProperties$1[name] = true; return true; } // Let the ARIA attribute hook validate ARIA attributes if (rARIA$1.test(name) || rARIACamel$1.test(name)) { return true; } if (lowerCasedName === 'innerhtml') { error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); warnedProperties$1[name] = true; return true; } if (lowerCasedName === 'aria') { error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.'); warnedProperties$1[name] = true; return true; } if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') { error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value); warnedProperties$1[name] = true; return true; } if (typeof value === 'number' && isNaN(value)) { error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name); warnedProperties$1[name] = true; return true; } var propertyInfo = getPropertyInfo(name); var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config. if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { var standardName = possibleStandardNames[lowerCasedName]; if (standardName !== name) { error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName); warnedProperties$1[name] = true; return true; } } else if (!isReserved && name !== lowerCasedName) { // Unknown attributes should have lowercase casing since that's how they // will be cased anyway with server rendering. error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName); warnedProperties$1[name] = true; return true; } if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { if (value) { error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name); } else { error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); } warnedProperties$1[name] = true; return true; } // Now that we've validated casing, do not validate // data types for reserved props if (isReserved) { return true; } // Warn when a known attribute is a bad type if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { warnedProperties$1[name] = true; return false; } // Warn when passing the strings 'false' or 'true' into a boolean prop if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) { error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value); warnedProperties$1[name] = true; return true; } return true; }; } var warnUnknownProperties = function (type, props, eventRegistry) { { var unknownProps = []; for (var key in props) { var isValid = validateProperty$1(type, key, props[key], eventRegistry); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } else if (unknownProps.length > 1) { error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } } }; function validateProperties$2(type, props, eventRegistry) { if (isCustomComponent(type, props)) { return; } warnUnknownProperties(type, props, eventRegistry); } var toArray = React.Children.toArray; // This is only used in DEV. // Each entry is `this.stack` from a currently executing renderer instance. // (There may be more than one because ReactDOMServer is reentrant). // Each stack is an array of frames which may contain nested stacks of elements. var currentDebugStacks = []; var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var ReactDebugCurrentFrame$1; var prevGetCurrentStackImpl = null; var getCurrentServerStackImpl = function () { return ''; }; var describeStackFrame = function (element) { return ''; }; var validatePropertiesInDevelopment = function (type, props) {}; var pushCurrentDebugStack = function (stack) {}; var pushElementToDebugStack = function (element) {}; var popCurrentDebugStack = function () {}; var hasWarnedAboutUsingContextAsConsumer = false; { ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; validatePropertiesInDevelopment = function (type, props) { validateProperties(type, props); validateProperties$1(type, props); validateProperties$2(type, props, null); }; describeStackFrame = function (element) { return describeUnknownElementTypeFrameInDEV(element.type, element._source, null); }; pushCurrentDebugStack = function (stack) { currentDebugStacks.push(stack); if (currentDebugStacks.length === 1) { // We are entering a server renderer. // Remember the previous (e.g. client) global stack implementation. prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack; ReactDebugCurrentFrame$1.getCurrentStack = getCurrentServerStackImpl; } }; pushElementToDebugStack = function (element) { // For the innermost executing ReactDOMServer call, var stack = currentDebugStacks[currentDebugStacks.length - 1]; // Take the innermost executing frame (e.g. <Foo>), var frame = stack[stack.length - 1]; // and record that it has one more element associated with it. frame.debugElementStack.push(element); // We only need this because we tail-optimize single-element // children and directly handle them in an inner loop instead of // creating separate frames for them. }; popCurrentDebugStack = function () { currentDebugStacks.pop(); if (currentDebugStacks.length === 0) { // We are exiting the server renderer. // Restore the previous (e.g. client) global stack implementation. ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl; prevGetCurrentStackImpl = null; } }; getCurrentServerStackImpl = function () { if (currentDebugStacks.length === 0) { // Nothing is currently rendering. return ''; } // ReactDOMServer is reentrant so there may be multiple calls at the same time. // Take the frames from the innermost call which is the last in the array. var frames = currentDebugStacks[currentDebugStacks.length - 1]; var stack = ''; // Go through every frame in the stack from the innermost one. for (var i = frames.length - 1; i >= 0; i--) { var frame = frames[i]; // Every frame might have more than one debug element stack entry associated with it. // This is because single-child nesting doesn't create materialized frames. // Instead it would push them through `pushElementToDebugStack()`. var debugElementStack = frame.debugElementStack; for (var ii = debugElementStack.length - 1; ii >= 0; ii--) { stack += describeStackFrame(debugElementStack[ii]); } } return stack; }; } var didWarnDefaultInputValue = false; var didWarnDefaultChecked = false; var didWarnDefaultSelectValue = false; var didWarnDefaultTextareaValue = false; var didWarnInvalidOptionChildren = false; var didWarnInvalidOptionInnerHTML = false; var didWarnAboutNoopUpdateForComponent = {}; var didWarnAboutBadClass = {}; var didWarnAboutModulePatternComponent = {}; var didWarnAboutDeprecatedWillMount = {}; var didWarnAboutUndefinedDerivedState = {}; var didWarnAboutUninitializedState = {}; var didWarnAboutLegacyLifecyclesAndDerivedState = {}; var valuePropNames = ['value', 'defaultValue']; var newlineEatingTags = { listing: true, pre: true, textarea: true }; // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; function validateDangerousTag(tag) { if (!validatedTagCache.hasOwnProperty(tag)) { if (!VALID_TAG_REGEX.test(tag)) { { throw Error( "Invalid tag: " + tag ); } } validatedTagCache[tag] = true; } } var styleNameCache = {}; var processStyleName = function (styleName) { if (styleNameCache.hasOwnProperty(styleName)) { return styleNameCache[styleName]; } var result = hyphenateStyleName(styleName); styleNameCache[styleName] = result; return result; }; function createMarkupForStyles(styles) { var serialized = ''; var delimiter = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var isCustomProperty = styleName.indexOf('--') === 0; var styleValue = styles[styleName]; { if (!isCustomProperty) { warnValidStyle$1(styleName, styleValue); } } if (styleValue != null) { serialized += delimiter + (isCustomProperty ? styleName : processStyleName(styleName)) + ':'; serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty); delimiter = ';'; } } return serialized || null; } function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass'; var warningKey = componentName + '.' + callerName; if (didWarnAboutNoopUpdateForComponent[warningKey]) { return; } error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName); didWarnAboutNoopUpdateForComponent[warningKey] = true; } } function shouldConstruct$1(Component) { return Component.prototype && Component.prototype.isReactComponent; } function getNonChildrenInnerMarkup(props) { var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return innerHTML.__html; } } else { var content = props.children; if (typeof content === 'string' || typeof content === 'number') { return escapeTextForBrowser(content); } } return null; } function flattenTopLevelChildren(children) { if (!React.isValidElement(children)) { return toArray(children); } var element = children; if (element.type !== REACT_FRAGMENT_TYPE) { return [element]; } var fragmentChildren = element.props.children; if (!React.isValidElement(fragmentChildren)) { return toArray(fragmentChildren); } var fragmentChildElement = fragmentChildren; return [fragmentChildElement]; } function flattenOptionChildren(children) { if (children === undefined || children === null) { return children; } var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function (child) { if (child == null) { return; } content += child; { if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') { didWarnInvalidOptionChildren = true; error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.'); } } }); return content; } var STYLE = 'style'; var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null, suppressHydrationWarning: null }; function createOpenTagMarkup(tagVerbatim, tagLowercase, props, namespace, makeStaticMarkup, isRootElement) { var ret = '<' + tagVerbatim; var isCustomComponent$1 = isCustomComponent(tagLowercase, props); for (var propKey in props) { if (!hasOwnProperty.call(props, propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (propKey === STYLE) { propValue = createMarkupForStyles(propValue); } var markup = null; if (isCustomComponent$1) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = createMarkupForCustomAttribute(propKey, propValue); } } else { markup = createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } return ret; } function validateRenderResult(child, type) { if (child === undefined) { { { throw Error( (getComponentNameFromType(type) || 'Component') + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." ); } } } } function resolve(child, context, threadID) { while (React.isValidElement(child)) { // Safe because we just checked it's an element. var element = child; var Component = element.type; { pushElementToDebugStack(element); } if (typeof Component !== 'function') { break; } processChild(element, Component); } // Extra closure so queue and replace can be captured properly function processChild(element, Component) { var isClass = shouldConstruct$1(Component); var publicContext = processContext(Component, context, threadID, isClass); var queue = []; var replace = false; var updater = { isMounted: function (publicInstance) { return false; }, enqueueForceUpdate: function (publicInstance) { if (queue === null) { warnNoop(publicInstance, 'forceUpdate'); return null; } }, enqueueReplaceState: function (publicInstance, completeState) { replace = true; queue = [completeState]; }, enqueueSetState: function (publicInstance, currentPartialState) { if (queue === null) { warnNoop(publicInstance, 'setState'); return null; } queue.push(currentPartialState); } }; var inst; if (isClass) { inst = new Component(element.props, publicContext, updater); if (typeof Component.getDerivedStateFromProps === 'function') { { if (inst.state === null || inst.state === undefined) { var componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutUninitializedState[componentName]) { error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, inst.state === null ? 'null' : 'undefined', componentName); didWarnAboutUninitializedState[componentName] = true; } } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. if (typeof Component.getDerivedStateFromProps === 'function' || typeof inst.getSnapshotBeforeUpdate === 'function') { var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; if (typeof inst.componentWillMount === 'function' && inst.componentWillMount.__suppressDeprecationWarning !== true) { foundWillMountName = 'componentWillMount'; } else if (typeof inst.UNSAFE_componentWillMount === 'function') { foundWillMountName = 'UNSAFE_componentWillMount'; } if (typeof inst.componentWillReceiveProps === 'function' && inst.componentWillReceiveProps.__suppressDeprecationWarning !== true) { foundWillReceivePropsName = 'componentWillReceiveProps'; } else if (typeof inst.UNSAFE_componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; } if (typeof inst.componentWillUpdate === 'function' && inst.componentWillUpdate.__suppressDeprecationWarning !== true) { foundWillUpdateName = 'componentWillUpdate'; } else if (typeof inst.UNSAFE_componentWillUpdate === 'function') { foundWillUpdateName = 'UNSAFE_componentWillUpdate'; } if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { var _componentName = getComponentNameFromType(Component) || 'Component'; var newApiName = typeof Component.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; if (!didWarnAboutLegacyLifecyclesAndDerivedState[_componentName]) { didWarnAboutLegacyLifecyclesAndDerivedState[_componentName] = true; error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); } } } } var partialState = Component.getDerivedStateFromProps.call(null, element.props, inst.state); { if (partialState === undefined) { var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutUndefinedDerivedState[_componentName2]) { error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', _componentName2); didWarnAboutUndefinedDerivedState[_componentName2] = true; } } } if (partialState != null) { inst.state = _assign({}, inst.state, partialState); } } } else { { if (Component.prototype && typeof Component.prototype.render === 'function') { var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutBadClass[_componentName3]) { error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', _componentName3, _componentName3); didWarnAboutBadClass[_componentName3] = true; } } } var componentIdentity = {}; prepareToUseHooks(componentIdentity); inst = Component(element.props, publicContext, updater); inst = finishHooks(Component, element.props, inst, publicContext); { // Support for module components is deprecated and is removed behind a flag. // Whether or not it would crash later, we want to show a good message in DEV first. if (inst != null && inst.render != null) { var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutModulePatternComponent[_componentName4]) { error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName4, _componentName4, _componentName4); didWarnAboutModulePatternComponent[_componentName4] = true; } } } // If the flag is on, everything is assumed to be a function component. // Otherwise, we also do the unfortunate dynamic checks. if ( inst == null || inst.render == null) { child = inst; validateRenderResult(child, Component); return; } } inst.props = element.props; inst.context = publicContext; inst.updater = updater; var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } if (typeof inst.UNSAFE_componentWillMount === 'function' || typeof inst.componentWillMount === 'function') { if (typeof inst.componentWillMount === 'function') { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for any component with the new gDSFP. if (typeof Component.getDerivedStateFromProps !== 'function') { { if ( inst.componentWillMount.__suppressDeprecationWarning !== true) { var _componentName5 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutDeprecatedWillMount[_componentName5]) { warn( // keep this warning in sync with ReactStrictModeWarning.js 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', _componentName5); didWarnAboutDeprecatedWillMount[_componentName5] = true; } } } inst.componentWillMount(); } } if (typeof inst.UNSAFE_componentWillMount === 'function' && typeof Component.getDerivedStateFromProps !== 'function') { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for any component with the new gDSFP. inst.UNSAFE_componentWillMount(); } if (queue.length) { var oldQueue = queue; var oldReplace = replace; queue = null; replace = false; if (oldReplace && oldQueue.length === 1) { inst.state = oldQueue[0]; } else { var nextState = oldReplace ? oldQueue[0] : inst.state; var dontMutate = true; for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { var partial = oldQueue[i]; var _partialState = typeof partial === 'function' ? partial.call(inst, nextState, element.props, publicContext) : partial; if (_partialState != null) { if (dontMutate) { dontMutate = false; nextState = _assign({}, nextState, _partialState); } else { _assign(nextState, _partialState); } } } inst.state = nextState; } } else { queue = null; } } child = inst.render(); { if (child === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. child = null; } } validateRenderResult(child, Component); var childContext; { if (typeof inst.getChildContext === 'function') { var _childContextTypes = Component.childContextTypes; if (typeof _childContextTypes === 'object') { childContext = inst.getChildContext(); for (var contextKey in childContext) { if (!(contextKey in _childContextTypes)) { { throw Error( (getComponentNameFromType(Component) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes." ); } } } } else { { error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', getComponentNameFromType(Component) || 'Unknown'); } } } if (childContext) { context = _assign({}, context, childContext); } } } return { child: child, context: context }; } var ReactDOMServerRenderer = /*#__PURE__*/function () { // TODO: type this more strictly: // DEV-only function ReactDOMServerRenderer(children, makeStaticMarkup, options) { var flatChildren = flattenTopLevelChildren(children); var topFrame = { type: null, // Assume all trees start in the HTML namespace (not totally true, but // this is what we did historically) domNamespace: HTML_NAMESPACE, children: flatChildren, childIndex: 0, context: emptyObject, footer: '' }; { topFrame.debugElementStack = []; } this.threadID = allocThreadID(); this.stack = [topFrame]; this.exhausted = false; this.currentSelectValue = null; this.previousWasTextNode = false; this.makeStaticMarkup = makeStaticMarkup; this.suspenseDepth = 0; // Context (new API) this.contextIndex = -1; this.contextStack = []; this.contextValueStack = []; // useOpaqueIdentifier ID this.uniqueID = 0; this.identifierPrefix = options && options.identifierPrefix || ''; { this.contextProviderStack = []; } } var _proto = ReactDOMServerRenderer.prototype; _proto.destroy = function destroy() { if (!this.exhausted) { this.exhausted = true; this.clearProviders(); freeThreadID(this.threadID); } } /** * Note: We use just two stacks regardless of how many context providers you have. * Providers are always popped in the reverse order to how they were pushed * so we always know on the way down which provider you'll encounter next on the way up. * On the way down, we push the current provider, and its context value *before* * we mutated it, onto the stacks. Therefore, on the way up, we always know which * provider needs to be "restored" to which value. * https://github.com/facebook/react/pull/12985#issuecomment-396301248 */ ; _proto.pushProvider = function pushProvider(provider) { var index = ++this.contextIndex; var context = provider.type._context; var threadID = this.threadID; validateContextBounds(context, threadID); var previousValue = context[threadID]; // Remember which value to restore this context to on our way up. this.contextStack[index] = context; this.contextValueStack[index] = previousValue; { // Only used for push/pop mismatch warnings. this.contextProviderStack[index] = provider; } // Mutate the current value. context[threadID] = provider.props.value; }; _proto.popProvider = function popProvider(provider) { var index = this.contextIndex; { if (index < 0 || provider !== this.contextProviderStack[index]) { error('Unexpected pop.'); } } var context = this.contextStack[index]; var previousValue = this.contextValueStack[index]; // "Hide" these null assignments from Flow by using `any` // because conceptually they are deletions--as long as we // promise to never access values beyond `this.contextIndex`. this.contextStack[index] = null; this.contextValueStack[index] = null; { this.contextProviderStack[index] = null; } this.contextIndex--; // Restore to the previous value we stored as we were walking down. // We've already verified that this context has been expanded to accommodate // this thread id, so we don't need to do it again. context[this.threadID] = previousValue; }; _proto.clearProviders = function clearProviders() { // Restore any remaining providers on the stack to previous values for (var index = this.contextIndex; index >= 0; index--) { var context = this.contextStack[index]; var previousValue = this.contextValueStack[index]; context[this.threadID] = previousValue; } }; _proto.read = function read(bytes) { if (this.exhausted) { return null; } var prevPartialRenderer = currentPartialRenderer; setCurrentPartialRenderer(this); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = Dispatcher; try { // Markup generated within <Suspense> ends up buffered until we know // nothing in that boundary suspended var out = ['']; var suspended = false; while (out[0].length < bytes) { if (this.stack.length === 0) { this.exhausted = true; freeThreadID(this.threadID); break; } var frame = this.stack[this.stack.length - 1]; if (suspended || frame.childIndex >= frame.children.length) { var footer = frame.footer; if (footer !== '') { this.previousWasTextNode = false; } this.stack.pop(); if (frame.type === 'select') { this.currentSelectValue = null; } else if (frame.type != null && frame.type.type != null && frame.type.type.$$typeof === REACT_PROVIDER_TYPE) { var provider = frame.type; this.popProvider(provider); } else if (frame.type === REACT_SUSPENSE_TYPE) { this.suspenseDepth--; var buffered = out.pop(); if (suspended) { suspended = false; // If rendering was suspended at this boundary, render the fallbackFrame var fallbackFrame = frame.fallbackFrame; if (!fallbackFrame) { { throw Error(true ? "ReactDOMServer did not find an internal fallback frame for Suspense. This is a bug in React. Please file an issue." : formatProdErrorMessage(303)); } } this.stack.push(fallbackFrame); out[this.suspenseDepth] += '<!--$!-->'; // Skip flushing output since we're switching to the fallback continue; } else { out[this.suspenseDepth] += buffered; } } // Flush output out[this.suspenseDepth] += footer; continue; } var child = frame.children[frame.childIndex++]; var outBuffer = ''; if (true) { pushCurrentDebugStack(this.stack); // We're starting work on this frame, so reset its inner stack. frame.debugElementStack.length = 0; } try { outBuffer += this.render(child, frame.context, frame.domNamespace); } catch (err) { if (err != null && typeof err.then === 'function') { if (enableSuspenseServerRenderer) { if (!(this.suspenseDepth > 0)) { { throw Error(true ? "A React component suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display." : formatProdErrorMessage(342)); } } suspended = true; } else { if (!false) { { throw Error(true ? "ReactDOMServer does not yet support Suspense." : formatProdErrorMessage(294)); } } } } else { throw err; } } finally { if (true) { popCurrentDebugStack(); } } if (out.length <= this.suspenseDepth) { out.push(''); } out[this.suspenseDepth] += outBuffer; } return out[0]; } finally { ReactCurrentDispatcher$1.current = prevDispatcher; setCurrentPartialRenderer(prevPartialRenderer); resetHooksState(); } }; _proto.render = function render(child, context, parentNamespace) { if (typeof child === 'string' || typeof child === 'number') { var text = '' + child; if (text === '') { return ''; } if (this.makeStaticMarkup) { return escapeTextForBrowser(text); } if (this.previousWasTextNode) { return '<!-- -->' + escapeTextForBrowser(text); } this.previousWasTextNode = true; return escapeTextForBrowser(text); } else { var nextChild; var _resolve = resolve(child, context, this.threadID); nextChild = _resolve.child; context = _resolve.context; if (nextChild === null || nextChild === false) { return ''; } else if (!React.isValidElement(nextChild)) { if (nextChild != null && nextChild.$$typeof != null) { // Catch unexpected special types early. var $$typeof = nextChild.$$typeof; if (!($$typeof !== REACT_PORTAL_TYPE)) { { throw Error( "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render." ); } } // Catch-all to prevent an infinite loop if React.Children.toArray() supports some new type. { { throw Error( "Unknown element-like object type: " + $$typeof.toString() + ". This is likely a bug in React. Please file an issue." ); } } } var nextChildren = toArray(nextChild); var frame = { type: null, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '' }; { frame.debugElementStack = []; } this.stack.push(frame); return ''; } // Safe because we just checked it's an element. var nextElement = nextChild; var elementType = nextElement.type; if (typeof elementType === 'string') { return this.renderDOM(nextElement, context, parentNamespace); } switch (elementType) { // TODO: LegacyHidden acts the same as a fragment. This only works // because we currently assume that every instance of LegacyHidden is // accompanied by a host component wrapper. In the hidden mode, the host // component is given a `hidden` attribute, which ensures that the // initial HTML is not visible. To support the use of LegacyHidden as a // true fragment, without an extra DOM node, we would have to hide the // initial HTML in some other way. case REACT_LEGACY_HIDDEN_TYPE: case REACT_DEBUG_TRACING_MODE_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_PROFILER_TYPE: case REACT_SUSPENSE_LIST_TYPE: case REACT_FRAGMENT_TYPE: { var _nextChildren = toArray(nextChild.props.children); var _frame = { type: null, domNamespace: parentNamespace, children: _nextChildren, childIndex: 0, context: context, footer: '' }; { _frame.debugElementStack = []; } this.stack.push(_frame); return ''; } case REACT_SUSPENSE_TYPE: { { var fallback = nextChild.props.fallback; if (fallback === undefined) { // If there is no fallback, then this just behaves as a fragment. var _nextChildren3 = toArray(nextChild.props.children); var _frame3 = { type: null, domNamespace: parentNamespace, children: _nextChildren3, childIndex: 0, context: context, footer: '' }; { _frame3.debugElementStack = []; } this.stack.push(_frame3); return ''; } var fallbackChildren = toArray(fallback); var _nextChildren2 = toArray(nextChild.props.children); var fallbackFrame = { type: null, domNamespace: parentNamespace, children: fallbackChildren, childIndex: 0, context: context, footer: '<!--/$-->' }; var _frame2 = { fallbackFrame: fallbackFrame, type: REACT_SUSPENSE_TYPE, domNamespace: parentNamespace, children: _nextChildren2, childIndex: 0, context: context, footer: '<!--/$-->' }; { _frame2.debugElementStack = []; fallbackFrame.debugElementStack = []; } this.stack.push(_frame2); this.suspenseDepth++; return '<!--$-->'; } } // eslint-disable-next-line-no-fallthrough case REACT_SCOPE_TYPE: { { { throw Error( "ReactDOMServer does not yet support scope components." ); } } } } if (typeof elementType === 'object' && elementType !== null) { switch (elementType.$$typeof) { case REACT_FORWARD_REF_TYPE: { var element = nextChild; var _nextChildren5; var componentIdentity = {}; prepareToUseHooks(componentIdentity); _nextChildren5 = elementType.render(element.props, element.ref); _nextChildren5 = finishHooks(elementType.render, element.props, _nextChildren5, element.ref); _nextChildren5 = toArray(_nextChildren5); var _frame5 = { type: null, domNamespace: parentNamespace, children: _nextChildren5, childIndex: 0, context: context, footer: '' }; { _frame5.debugElementStack = []; } this.stack.push(_frame5); return ''; } case REACT_MEMO_TYPE: { var _element = nextChild; var _nextChildren6 = [React.createElement(elementType.type, _assign({ ref: _element.ref }, _element.props))]; var _frame6 = { type: null, domNamespace: parentNamespace, children: _nextChildren6, childIndex: 0, context: context, footer: '' }; { _frame6.debugElementStack = []; } this.stack.push(_frame6); return ''; } case REACT_PROVIDER_TYPE: { var provider = nextChild; var nextProps = provider.props; var _nextChildren7 = toArray(nextProps.children); var _frame7 = { type: provider, domNamespace: parentNamespace, children: _nextChildren7, childIndex: 0, context: context, footer: '' }; { _frame7.debugElementStack = []; } this.pushProvider(provider); this.stack.push(_frame7); return ''; } case REACT_CONTEXT_TYPE: { var reactContext = nextChild.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. { if (reactContext._context === undefined) { // This may be because it's a Context (rather than a Consumer). // Or it may be because it's older React where they're the same thing. // We only want to warn if we're sure it's a new React. if (reactContext !== reactContext.Consumer) { if (!hasWarnedAboutUsingContextAsConsumer) { hasWarnedAboutUsingContextAsConsumer = true; error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } } } else { reactContext = reactContext._context; } } var _nextProps = nextChild.props; var threadID = this.threadID; validateContextBounds(reactContext, threadID); var nextValue = reactContext[threadID]; var _nextChildren8 = toArray(_nextProps.children(nextValue)); var _frame8 = { type: nextChild, domNamespace: parentNamespace, children: _nextChildren8, childIndex: 0, context: context, footer: '' }; { _frame8.debugElementStack = []; } this.stack.push(_frame8); return ''; } // eslint-disable-next-line-no-fallthrough case REACT_LAZY_TYPE: { var _element2 = nextChild; var lazyComponent = nextChild.type; // Attempt to initialize lazy component regardless of whether the // suspense server-side renderer is enabled so synchronously // resolved constructors are supported. var payload = lazyComponent._payload; var init = lazyComponent._init; var result = init(payload); var _nextChildren9 = [React.createElement(result, _assign({ ref: _element2.ref }, _element2.props))]; var _frame9 = { type: null, domNamespace: parentNamespace, children: _nextChildren9, childIndex: 0, context: context, footer: '' }; { _frame9.debugElementStack = []; } this.stack.push(_frame9); return ''; } } } var info = ''; { var owner = nextElement._owner; if (elementType === undefined || typeof elementType === 'object' && elementType !== null && Object.keys(elementType).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; } var ownerName = owner ? getComponentNameFromType(owner) : null; if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } { { throw Error( "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (elementType == null ? elementType : typeof elementType) + "." + info ); } } } }; _proto.renderDOM = function renderDOM(element, context, parentNamespace) { var tag = element.type; var namespace = parentNamespace; if (parentNamespace === HTML_NAMESPACE) { namespace = getIntrinsicNamespace(tag); } var props = element.props; { if (namespace === HTML_NAMESPACE) { var isCustomComponent$1 = isCustomComponent(tag, props); // Should this check be gated by parent namespace? Not sure we want to // allow <SVG> or <mATH>. if (!isCustomComponent$1 && tag.toLowerCase() !== element.type) { error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', element.type); } } } validateDangerousTag(tag); if (tag === 'input') { { checkControlledValueProps('input', props); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) { error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type); didWarnDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) { error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', 'A component', props.type); didWarnDefaultInputValue = true; } } props = _assign({ type: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: props.value != null ? props.value : props.defaultValue, checked: props.checked != null ? props.checked : props.defaultChecked }); } else if (tag === 'textarea') { { checkControlledValueProps('textarea', props); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) { error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components'); didWarnDefaultTextareaValue = true; } } var initialValue = props.value; if (initialValue == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var textareaChildren = props.children; if (textareaChildren != null) { { error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.'); } if (!(defaultValue == null)) { { throw Error( "If you supply `defaultValue` on a <textarea>, do not pass children." ); } } if (isArray(textareaChildren)) { if (!(textareaChildren.length <= 1)) { { throw Error( "<textarea> can only have at most one child." ); } } textareaChildren = textareaChildren[0]; } defaultValue = '' + textareaChildren; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } props = _assign({}, props, { value: undefined, children: '' + initialValue }); } else if (tag === 'select') { { checkControlledValueProps('select', props); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var propNameIsArray = isArray(props[propName]); if (props.multiple && !propNameIsArray) { error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName); } else if (!props.multiple && propNameIsArray) { error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName); } } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) { error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components'); didWarnDefaultSelectValue = true; } } this.currentSelectValue = props.value != null ? props.value : props.defaultValue; props = _assign({}, props, { value: undefined }); } else if (tag === 'option') { var selected = null; var selectValue = this.currentSelectValue; if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { { if (props.dangerouslySetInnerHTML != null) { if (!didWarnInvalidOptionInnerHTML) { didWarnInvalidOptionInnerHTML = true; error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.'); } } } value = flattenOptionChildren(props.children); } selected = false; if (isArray(selectValue)) { // multiple for (var j = 0; j < selectValue.length; j++) { if ('' + selectValue[j] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } props = _assign({ selected: undefined }, props, { selected: selected }); } } { validatePropertiesInDevelopment(tag, props); } assertValidProps(tag, props); var out = createOpenTagMarkup(element.type, tag, props, namespace, this.makeStaticMarkup, this.stack.length === 1); var footer = ''; if (omittedCloseTags.hasOwnProperty(tag)) { out += '/>'; } else { out += '>'; footer = '</' + element.type + '>'; } var children; var innerMarkup = getNonChildrenInnerMarkup(props); if (innerMarkup != null) { children = []; if (newlineEatingTags.hasOwnProperty(tag) && innerMarkup.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> out += '\n'; } out += innerMarkup; } else { children = toArray(props.children); } var frame = { domNamespace: getChildNamespace(parentNamespace, element.type), type: tag, children: children, childIndex: 0, context: context, footer: footer }; { frame.debugElementStack = []; } this.stack.push(frame); this.previousWasTextNode = false; return out; }; return ReactDOMServerRenderer; }(); /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://reactjs.org/docs/react-dom-server.html#rendertostring */ function renderToString(element, options) { var renderer = new ReactDOMServerRenderer(element, false, options); try { var markup = renderer.read(Infinity); return markup; } finally { renderer.destroy(); } } /** * Similar to renderToString, except this doesn't create extra DOM attributes * such as data-react-id that React uses internally. * See https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup */ function renderToStaticMarkup(element, options) { var renderer = new ReactDOMServerRenderer(element, true, options); try { var markup = renderer.read(Infinity); return markup; } finally { renderer.destroy(); } } function renderToNodeStream() { { { throw Error( "ReactDOMServer.renderToNodeStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToString() instead." ); } } } function renderToStaticNodeStream() { { { throw Error( "ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available in the browser. Use ReactDOMServer.renderToStaticMarkup() instead." ); } } } exports.renderToNodeStream = renderToNodeStream; exports.renderToStaticMarkup = renderToStaticMarkup; exports.renderToStaticNodeStream = renderToStaticNodeStream; exports.renderToString = renderToString; exports.version = ReactVersion; })));
blueocean-material-icons/src/js/components/svg-icons/content/drafts.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ContentDrafts = (props) => ( <SvgIcon {...props}> <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"/> </SvgIcon> ); ContentDrafts.displayName = 'ContentDrafts'; ContentDrafts.muiName = 'SvgIcon'; export default ContentDrafts;
src/components/Content.react.js
AllenFang/react-babel-demo
import React from 'react'; export default React.createClass({ render() { return ( <div>Current value: {this.props.count}</div> ) } });
packages/react-art/npm/Circle.js
silvestrijonathan/react
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @typechecks * * Example usage: * <Circle * radius={10} * stroke="green" * strokeWidth={3} * fill="blue" * /> * */ 'use strict'; var assign = require('object-assign'); var PropTypes = require('prop-types'); var React = require('react'); var ReactART = require('react-art'); var createReactClass = require('create-react-class'); var Path = ReactART.Path; var Shape = ReactART.Shape; /** * Circle is a React component for drawing circles. Like other ReactART * components, it must be used in a <Surface>. */ var Circle = createReactClass({ displayName: 'Circle', propTypes: { radius: PropTypes.number.isRequired, }, render: function render() { var radius = this.props.radius; var path = Path() .moveTo(0, -radius) .arc(0, radius * 2, radius) .arc(0, radius * -2, radius) .close(); return React.createElement(Shape, assign({}, this.props, {d: path})); }, }); module.exports = Circle;
src/icons/FlightLandIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FlightLandIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M5 38h38v4H5zm14.37-11.46l8.69 2.33 10.63 2.85c1.6.43 3.24-.52 3.67-2.12.43-1.6-.52-3.24-2.12-3.67l-10.63-2.85L24.1 5.04 20.23 4v16.56L10.3 17.9l-1.86-4.64-2.9-.78v10.35l3.21.86 10.62 2.85z"/></svg>;} };
clients/libs/webpage/src/lib/plugins/pressure/components/targets.js
nossas/bonde-client
import React from 'react' import PropTypes from 'prop-types' import { FormattedMessage } from 'react-intl' import { arrayUtils, pressureUtils } from '../utils' if (require('exenv').canUseDOM) require('./targets.scss') const parseTarget = target => { const targetSplit = target.split('<') const valid = targetSplit.length === 2 return valid ? { name: targetSplit[0].trim(), value: targetSplit[1].replace('>', '') } : null } class TargetList extends React.Component { constructor (props) { super(props) this.state = { targets: props.targets, selectedTargets: [] } } render () { const { targets } = this.state const pressureType = pressureUtils.getType(targets) const isPressurePhone = pressureType === pressureUtils.PRESSURE_TYPE_PHONE return ( <div className='target-list px2 py1'> <div className='target-list-label bold'> <FormattedMessage id='pressure-widget--target-list.label.email' defaultMessage={` Quem você vai pressionar ({targetsCount} {targetsCount, plural, one {alvo} other {alvos} }) `} values={{ targetsCount: String(arrayUtils.clean(targets).length) }} /> </div> <div className='target-list-container clearfix'> <div className='target-list-wrapper clearfix'> {targets.length > 0 && targets.map((obj, index) => { const target = parseTarget(obj) return !target ? null : ( <label key={`target-item-${index}`} className='target-item left py1 px2 mr1 bg-white rounded' > <p className='black h6 m0'> <span className='target-name bold flex'>{target.name}</span> {!isPressurePhone && <span className='target-value'>{target.value}</span>} </p> </label> ) })} </div> </div> </div> ) } } TargetList.propTypes = { targets: PropTypes.arrayOf(PropTypes.string) } TargetList.defaultProps = { targets: [] } export default TargetList
src/server.js
transitlinks/web-app
import { getLog } from './core/log'; const log = getLog('server'); import 'babel-polyfill'; import './serverIntlPolyfill'; import path from 'path'; import http from 'http'; import https from 'https'; import express from 'express'; import cookieParser from 'cookie-parser'; import requestLanguage from 'express-request-language'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; import expressSession from 'express-session'; import pgSessionStore from 'connect-pg-simple'; import { Pool } from 'pg'; import jwt from 'jsonwebtoken'; import multer from 'multer'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from './components/Html'; import { ErrorPage } from './routes/error/ErrorPage'; import errorPageStyle from './routes/error/ErrorPage.css'; import PrettyError from 'pretty-error'; import passport from './core/passport'; import models from './data/models'; import schema from './data/schema'; import { loadFixtures } from './data/sequelize'; import routes from './routes'; import { initEndpoints } from './routes'; import { APP_ENV, HTTP_HOST, HTTP_PORT, STORAGE_PATH, locales } from './config'; import assets from './assets'; // eslint-disable-line import/no-unresolved //import { HTTP_HOST, HTTP_PORT, locales } from './config'; if (process.env.TEST_ENV === 'test' && APP_ENV !== 'test') { console.log("Not allowed to run in test mode with wrong environment settings"); console.log("TEST_ENV", process.env.TEST_ENV); console.log("APP_ENV", APP_ENV); process.exit(1); } const app = express(); app.schema = schema; app.assets = assets; // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; //global.navigator.userAgent = 'all'; //global.navigator = { navigator: 'all' }; // Register Node.js middleware app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(requestLanguage({ languages: locales, queryName: 'lang', cookie: { name: 'lang', options: { path: '/', maxAge: 3650 * 24 * 3600 * 1000, // 10 years in miliseconds }, url: '/lang/{language}', }, })); app.use(bodyParser.urlencoded({ extended: true, limit: '100mb' })); app.use(bodyParser.json({ limit: '100mb' })); const instanceMediaPath = STORAGE_PATH || path.join(__dirname, 'public'); const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, instanceMediaPath) }, filename: (req, file, cb) => { cb(null, file.fieldname + '-' + Date.now()) } }); app.use(multer({ storage }).single('file')); // Authentication /* app.use(expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, getToken: req => req.cookies.id_token, })); */ const poolSettings = { max: 10, connectionString: process.env.DB_URL }; if (APP_ENV === 'stage') { poolSettings.ssl = { rejectUnauthorized: false }; } const pool = new Pool(poolSettings); const pgSession = pgSessionStore(expressSession); app.use(expressSession({ store: new pgSession({ pool }), secret: 'secret', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); app.passport = passport; initEndpoints(app); // Error handling const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars log.error(pe.render(err)); // eslint-disable-line no-console const statusCode = err.status || 500; const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} style={errorPageStyle._getCss()} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPage error={err} />)} </Html> ); res.status(statusCode); res.send(`<!doctype html>${html}`); }); const force = process.env.TEST_ENV === 'test'; // Launch the server /* eslint-disable no-console */ models.sync({ force: false, logging: console.log }).catch(err => console.error(err.stack)).then(() => { loadFixtures(); app.listen(HTTP_PORT, () => { log.info(`The server is running at http://${HTTP_HOST}:${HTTP_PORT}/`); }); }); /* eslint-enable no-console */
app/javascript/mastodon/features/account/components/header.js
5thfloor/ichiji-social
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Button from 'mastodon/components/button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { autoPlayGif, me, isStaff } from 'mastodon/initial_state'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import Avatar from 'mastodon/components/avatar'; import { shortNumberFormat } from 'mastodon/utils/numbers'; import { NavLink } from 'react-router-dom'; import DropdownMenuContainer from 'mastodon/containers/dropdown_menu_container'; const messages = defineMessages({ unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, follow: { id: 'account.follow', defaultMessage: 'Follow' }, cancel_follow_request: { id: 'account.cancel_follow_request', defaultMessage: 'Cancel follow request' }, requested: { id: 'account.requested', defaultMessage: 'Awaiting approval. Click to cancel follow request' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' }, linkVerifiedOn: { id: 'account.link_verified_on', defaultMessage: 'Ownership of this link was checked on {date}' }, account_locked: { id: 'account.locked_info', defaultMessage: 'This account privacy status is set to locked. The owner manually reviews who can follow them.' }, mention: { id: 'account.mention', defaultMessage: 'Mention @{name}' }, direct: { id: 'account.direct', defaultMessage: 'Direct message @{name}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' }, block: { id: 'account.block', defaultMessage: 'Block @{name}' }, mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, report: { id: 'account.report', defaultMessage: 'Report @{name}' }, share: { id: 'account.share', defaultMessage: 'Share @{name}\'s profile' }, media: { id: 'account.media', defaultMessage: 'Media' }, blockDomain: { id: 'account.block_domain', defaultMessage: 'Hide everything from {domain}' }, unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unhide {domain}' }, hideReblogs: { id: 'account.hide_reblogs', defaultMessage: 'Hide boosts from @{name}' }, showReblogs: { id: 'account.show_reblogs', defaultMessage: 'Show boosts from @{name}' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, endorse: { id: 'account.endorse', defaultMessage: 'Feature on profile' }, unendorse: { id: 'account.unendorse', defaultMessage: 'Don\'t feature on profile' }, add_or_remove_from_list: { id: 'account.add_or_remove_from_list', defaultMessage: 'Add or Remove from lists' }, admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' }, }); const dateFormatOptions = { month: 'short', day: 'numeric', year: 'numeric', hour12: false, hour: '2-digit', minute: '2-digit', }; export default @injectIntl class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, identity_props: ImmutablePropTypes.list, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, domain: PropTypes.string.isRequired, }; openEditProfile = () => { window.open('/settings/profile', '_blank'); } isStatusesPageActive = (match, location) => { if (!match) { return false; } return !location.pathname.match(/\/(followers|following)\/?$/); } _updateEmojis () { const node = this.node; if (!node || autoPlayGif) { return; } const emojis = node.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; if (emoji.classList.contains('status-emoji')) { continue; } emoji.classList.add('status-emoji'); emoji.addEventListener('mouseenter', this.handleEmojiMouseEnter, false); emoji.addEventListener('mouseleave', this.handleEmojiMouseLeave, false); } } componentDidMount () { this._updateEmojis(); } componentDidUpdate () { this._updateEmojis(); } handleEmojiMouseEnter = ({ target }) => { target.src = target.getAttribute('data-original'); } handleEmojiMouseLeave = ({ target }) => { target.src = target.getAttribute('data-static'); } setRef = (c) => { this.node = c; } render () { const { account, intl, domain, identity_proofs } = this.props; if (!account) { return null; } let info = []; let actionBtn = ''; let lockedIcon = ''; let menu = []; if (me !== account.get('id') && account.getIn(['relationship', 'followed_by'])) { info.push(<span key='followed_by' className='relationship-tag'><FormattedMessage id='account.follows_you' defaultMessage='Follows you' /></span>); } else if (me !== account.get('id') && account.getIn(['relationship', 'blocking'])) { info.push(<span key='blocked' className='relationship-tag'><FormattedMessage id='account.blocked' defaultMessage='Blocked' /></span>); } if (me !== account.get('id') && account.getIn(['relationship', 'muting'])) { info.push(<span key='muted' className='relationship-tag'><FormattedMessage id='account.muted' defaultMessage='Muted' /></span>); } else if (me !== account.get('id') && account.getIn(['relationship', 'domain_blocking'])) { info.push(<span key='domain_blocked' className='relationship-tag'><FormattedMessage id='account.domain_blocked' defaultMessage='Domain hidden' /></span>); } if (me !== account.get('id')) { if (!account.get('relationship')) { // Wait until the relationship is loaded actionBtn = ''; } else if (account.getIn(['relationship', 'requested'])) { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.cancel_follow_request)} title={intl.formatMessage(messages.requested)} onClick={this.props.onFollow} />; } else if (!account.getIn(['relationship', 'blocking'])) { actionBtn = <Button disabled={account.getIn(['relationship', 'blocked_by'])} className={classNames('logo-button', { 'button--destructive': account.getIn(['relationship', 'following']) })} text={intl.formatMessage(account.getIn(['relationship', 'following']) ? messages.unfollow : messages.follow)} onClick={this.props.onFollow} />; } else if (account.getIn(['relationship', 'blocking'])) { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.props.onBlock} />; } } else { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.edit_profile)} onClick={this.openEditProfile} />; } if (account.get('moved') && !account.getIn(['relationship', 'following'])) { actionBtn = ''; } if (account.get('locked')) { lockedIcon = <Icon id='lock' title={intl.formatMessage(messages.account_locked)} />; } if (account.get('id') !== me) { menu.push({ text: intl.formatMessage(messages.mention, { name: account.get('username') }), action: this.props.onMention }); menu.push({ text: intl.formatMessage(messages.direct, { name: account.get('username') }), action: this.props.onDirect }); menu.push(null); } if ('share' in navigator) { menu.push({ text: intl.formatMessage(messages.share, { name: account.get('username') }), action: this.handleShare }); menu.push(null); } if (account.get('id') === me) { menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' }); menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' }); menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' }); menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' }); menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' }); menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' }); menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' }); } else { if (account.getIn(['relationship', 'following'])) { if (account.getIn(['relationship', 'showing_reblogs'])) { menu.push({ text: intl.formatMessage(messages.hideReblogs, { name: account.get('username') }), action: this.props.onReblogToggle }); } else { menu.push({ text: intl.formatMessage(messages.showReblogs, { name: account.get('username') }), action: this.props.onReblogToggle }); } menu.push({ text: intl.formatMessage(account.getIn(['relationship', 'endorsed']) ? messages.unendorse : messages.endorse), action: this.props.onEndorseToggle }); menu.push({ text: intl.formatMessage(messages.add_or_remove_from_list), action: this.props.onAddToList }); menu.push(null); } if (account.getIn(['relationship', 'muting'])) { menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.props.onMute }); } else { menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.props.onMute }); } if (account.getIn(['relationship', 'blocking'])) { menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.props.onBlock }); } else { menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.props.onBlock }); } menu.push({ text: intl.formatMessage(messages.report, { name: account.get('username') }), action: this.props.onReport }); } if (account.get('acct') !== account.get('username')) { const domain = account.get('acct').split('@')[1]; menu.push(null); if (account.getIn(['relationship', 'domain_blocking'])) { menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.props.onUnblockDomain }); } else { menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.props.onBlockDomain }); } } if (account.get('id') !== me && isStaff) { menu.push(null); menu.push({ text: intl.formatMessage(messages.admin_account, { name: account.get('username') }), href: `/admin/accounts/${account.get('id')}` }); } const content = { __html: account.get('note_emojified') }; const displayNameHtml = { __html: account.get('display_name_html') }; const fields = account.get('fields'); const badge = account.get('bot') ? (<div className='account-role bot'><FormattedMessage id='account.badges.bot' defaultMessage='Bot' /></div>) : null; const acct = account.get('acct').indexOf('@') === -1 && domain ? `${account.get('acct')}@${domain}` : account.get('acct'); return ( <div className={classNames('account__header', { inactive: !!account.get('moved') })} ref={this.setRef}> <div className='account__header__image'> <div className='account__header__info'> {info} </div> <img src={autoPlayGif ? account.get('header') : account.get('header_static')} alt='' className='parallax' /> </div> <div className='account__header__bar'> <div className='account__header__tabs'> <a className='avatar' href={account.get('url')} rel='noopener' target='_blank'> <Avatar account={account} size={90} /> </a> <div className='spacer' /> <div className='account__header__tabs__buttons'> {actionBtn} <DropdownMenuContainer items={menu} icon='ellipsis-v' size={24} direction='right' /> </div> </div> <div className='account__header__tabs__name'> <h1> <span dangerouslySetInnerHTML={displayNameHtml} /> {badge} <small>@{acct} {lockedIcon}</small> </h1> </div> <div className='account__header__extra'> <div className='account__header__bio'> { (fields.size > 0 || identity_proofs.size > 0) && ( <div className='account__header__fields'> {identity_proofs.map((proof, i) => ( <dl key={i}> <dt dangerouslySetInnerHTML={{ __html: proof.get('provider') }} /> <dd className='verified'> <a href={proof.get('proof_url')} target='_blank' rel='noopener'><span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(proof.get('updated_at'), dateFormatOptions) })}> <Icon id='check' className='verified__mark' /> </span></a> <a href={proof.get('profile_url')} target='_blank' rel='noopener'><span dangerouslySetInnerHTML={{ __html: ' '+proof.get('provider_username') }} /></a> </dd> </dl> ))} {fields.map((pair, i) => ( <dl key={i}> <dt dangerouslySetInnerHTML={{ __html: pair.get('name_emojified') }} title={pair.get('name')} /> <dd className={pair.get('verified_at') && 'verified'} title={pair.get('value_plain')}> {pair.get('verified_at') && <span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(pair.get('verified_at'), dateFormatOptions) })}><Icon id='check' className='verified__mark' /></span>} <span dangerouslySetInnerHTML={{ __html: pair.get('value_emojified') }} /> </dd> </dl> ))} </div> )} {account.get('note').length > 0 && account.get('note') !== '<p></p>' && <div className='account__header__content' dangerouslySetInnerHTML={content} />} </div> <div className='account__header__extra__links'> <NavLink isActive={this.isStatusesPageActive} activeClassName='active' to={`/accounts/${account.get('id')}`} title={intl.formatNumber(account.get('statuses_count'))}> <strong>{shortNumberFormat(account.get('statuses_count'))}</strong> <FormattedMessage id='account.posts' defaultMessage='Toots' /> </NavLink> <NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/following`} title={intl.formatNumber(account.get('following_count'))}> <strong>{shortNumberFormat(account.get('following_count'))}</strong> <FormattedMessage id='account.follows' defaultMessage='Follows' /> </NavLink> <NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/followers`} title={intl.formatNumber(account.get('followers_count'))}> <strong>{shortNumberFormat(account.get('followers_count'))}</strong> <FormattedMessage id='account.followers' defaultMessage='Followers' /> </NavLink> </div> </div> </div> </div> ); } }
Components/ResourceMixin.js
tradle/tim
import _ from 'lodash' import Icon from 'react-native-vector-icons/Ionicons'; import React from 'react' import { Text, View, ActivityIndicator, Linking, TouchableOpacity } from 'react-native' import {Column as Col, Row} from 'react-native-flexbox-grid' // import JSONTree from 'react-native-json-tree' import constants from '@tradle/constants' const { TYPE } = constants const { PROFILE, ORGANIZATION, MONEY, MESSAGE, FORM } = constants.TYPES import StyleSheet from '../StyleSheet' import PhotoList from './PhotoList' import Accordion from './Accordion' import Actions from '../Actions/Actions' import PageView from './PageView' import defaultBankStyle from '../styles/defaultBankStyle.json' import utils, { translate, formatNumber } from '../utils/utils' import platformStyles from '../styles/platform' import buttonStyles from '../styles/buttonStyles' import Image from './Image' import uiUtils from '../utils/uiUtils' import GridHeader from './GridHeader' import GridRow from './GridRow' import Markdown from './Markdown' import ActionSheet from './ActionSheet' const RESOURCE_VIEW = 'ResourceView' const MESSAGE_VIEW = 'MessageView' const APPLICATION_VIEW = 'ApplicationView' const RESOURCE_LIST = 'ResourceList' const CHECK_VIEW = 'CheckView' const debug = utils.logger('ResourceMixin') const NOT_SPECIFIED = '[not specified]' const TERMS_AND_CONDITIONS = 'tradle.TermsAndConditions' const APPLICATION = 'tradle.Application' const CHECK = 'tradle.Check' const MODIFICATION = 'tradle.Modification' const DEFAULT_CURRENCY_SYMBOL = '$' const skipLabelsInJSON = { 'tradle.PhotoID': { 'address': ['full'] } } const hideGroupInJSON = { 'tradle.PhotoID': ['address'] } const showCollapsedMap = { 'tradle.PhotoID': 'scanJson', 'tradle.SanctionsCheck': 'rawData', 'tradle.CentrixCheck': 'rawData', 'tradle.CorporationExistsCheck': 'rawData', 'tradle.documentChecker.Check': 'rawData' } var component var ResourceMixin = { showRefResource(resource, prop, isDataLineage) { let type = utils.getType(resource) let model = utils.getModel(type); let title = utils.getDisplayName({ resource }) let modelTitle = translate(model) if (title && title.length) title = title + ' -- ' + modelTitle else title = modelTitle let isMessageView, isApplicationView if (type === APPLICATION) isApplicationView = true else if (!utils.isStub(resource)) isMessageView = utils.isMessage(resource) else isMessageView = (type !== ORGANIZATION && type !== PROFILE) const isCheck = model.subClassOf === CHECK let {bankStyle, search, currency, locale, country, navigator, application} = this.props if (isMessageView) { let r = this.props.resource let isVerifier = utils.getModel(utils.getType(r)).subClassOf === CHECK && application && utils.isRM(application) let route = { componentName: isCheck && CHECK_VIEW || MESSAGE_VIEW, backButtonTitle: 'Back', title, passProps: { bankStyle, resource, search, currency, locale, country, isThisVersion: isDataLineage } } if (isVerifier) { route.rightButtonTitle = 'Done' _.extend(route.passProps, { isVerifier, application }) } navigator.push(route) } else if (isApplicationView) { navigator.push({ title: title, componentName: APPLICATION_VIEW, backButtonTitle: 'Back', passProps: { resource, search, bankStyle, currency, locale, application: resource } }) } else { navigator.push({ title: title, componentName: RESOURCE_VIEW, backButtonTitle: 'Back', passProps: { resource, prop, bankStyle: bankStyle || defaultBankStyle, currency: this.props.currency, locale } }) } }, showResources(resource, prop) { const { navigator, currency, locale, bankStyle } = this.props navigator.push({ title: translate(prop, utils.getModel(resource[TYPE])), backButtonTitle: 'Back', componentName: RESOURCE_LIST, passProps: { modelName: prop.items.ref, filter: '', resource, prop, bankStyle: bankStyle || defaultBankStyle, currency, locale } }); }, renderItems({value, prop, cancelItem, editItem, component, showResourceProperty}) { let { bankStyle, navigator, resource, currency, locale } = this.props let linkColor = (bankStyle && bankStyle.linkColor) || defaultBankStyle.linkColor let itemsMeta = prop.items.properties; let pModel let ref = prop.items.ref; if (!itemsMeta) { if (ref) { pModel = utils.getModel(ref); itemsMeta = pModel.properties; } } let counter = 0; let vCols = pModel && pModel.viewCols if (!vCols) { vCols = [] for (let p in itemsMeta) { if (p.charAt(0) !== '_' && !itemsMeta[p].hidden) vCols.push(p); } } let cnt = value.length; let isView = component && component.name === 'ShowPropertiesView' let isWeb = utils.isWeb() return value.map((v) => { let ret = []; counter++; if (!prop.inlined && !pModel.inlined) { let item = this.renderItem({editItem, cancelItem, prop, v}) let sep = counter !== cnt && <View style={styles.itemSeparator}></View> return <View key={this.getNextKey()} style={{paddingVertical: 10, paddingLeft:10}} > {item} {sep} </View> } let displayName let hadCancel let hasEdit vCols.forEach((p) => { let itemMeta = itemsMeta[p]; let { type, displayAs, displayName, range, ref, skipLabel, items } = itemMeta let pVal = v[p] if (!pVal && !displayAs) { if (type !== 'boolean' || pVal !== false) return } if (displayName && !editItem) { let displayingPart = type === 'object' && pVal.title || pVal if (typeof displayingPart === 'object') { if (itemMeta.ref && displayingPart[TYPE] && showResourceProperty) { // displayingPart = JSON.stringify(utils.getDisplayName({resource: displayingPart}), null, 2) ret.push(showResourceProperty(displayingPart)) return } displayingPart = JSON.stringify(displayingPart, null, 2) ret.push(<View style={{flexDirection: isWeb && 'row' || 'column', paddingVertical: 3}}> <View style={styles.itemContent}> <Text style={skipLabel ? {height: 0} : [styles.itemText, {color: '#999999'}]}>{itemMeta.skipLabel ? '' : itemMeta.title || utils.makeLabel(p)}</Text> <Text style={styles.itemText}>{displayingPart}</Text> </View> {!isView && <View style={styles.textContainer}/>} </View>) } else { ret.push(<View style={styles.itemContent}> <Text style={skipLabel ? {height: 0} : [styles.itemText, {color: '#999999', fontSize: 18}]}>{itemMeta.skipLabel ? '' : itemMeta.title || utils.makeLabel(p)}</Text> <Text style={styles.itemHighlight}>{displayingPart}</Text> </View>) } return } let value; let isDisplayName = displayAs if (isDisplayName) value = utils.templateIt(itemMeta, v, pModel) else if (type === 'date') value = utils.formatDate(pVal); else if (type === 'boolean') value = pVal ? 'Yes' : 'No' else if (type === 'array') { let iref = items.ref if (iref) { if (p == 'photos') { ret.push( <PhotoList photos={v.photos} navigator={navigator} numberInRow={4} resource={resource} isView={true}/> ); return } if (utils.isEnum(iref)) { ret.push( <View style={{flexDirection: isWeb && 'row' || 'column', paddingVertical: 3}}> <View style={styles.itemContent}> <Text style={skipLabel ? {height: 0} : [styles.itemText, {color: '#999999'}]}>{itemMeta.skipLabel ? '' : itemMeta.title || utils.makeLabel(p)}</Text> <View style={styles.enumValue} key={this.getNextKey()}> {pVal.map((v, i) => <Text style={styles.itemText}>{v.title}</Text>)} </View> </View> {!isView && <View style={styles.textContainer}/>} </View> ) return } } } else if (type !== 'object') { // if (p == 'photos') { // ret.push( // <PhotoList photos={v.photos} navigator={navigator} numberInRow={4} resource={resource} isView={true}/> // ); // return // } // else value = pVal; } else if (range === 'json') { // let json = {[displayName]: pVal} ret.push(this.showJson({ json: pVal, prop: itemMeta, isView: true })) return } else if (ref) { if (ref === MONEY) { let pCurrency = pVal.currency if (!pCurrency) { pCurrency = currency && currency.symbol if (!pCurrency) pCurrency = DEFAULT_CURRENCY_SYMBOL } let c = utils.normalizeCurrencySymbol(pCurrency) // value = (c || pCurrency) + pVal.value value = (c || pCurrency) + formatNumber(itemMeta, pVal.value, locale) } else value = pVal.title || utils.getDisplayName({ resource: pVal, model: utils.getModel(ref) }) } else value = pVal.title; if (!value) return let item = <View style={{flexDirection: isWeb && 'row' || 'column', paddingVertical: 3}}> <View style={styles.itemContent}> <Text style={skipLabel ? {height: 0} : [styles.itemText, {color: '#999999'}]}>{skipLabel ? '' : itemMeta.title || utils.makeLabel(p)}</Text> <Text style={styles.itemText}>{value}</Text> </View> {!isView && <View style={styles.textContainer}/>} </View> if (editItem && !hasEdit) { hasEdit = true let cancel if (cancelItem && !hadCancel) { hadCancel = true cancel = <View style={styles.cancelIcon}> <TouchableOpacity underlayColor='transparent' onPress={cancelItem.bind(this, prop, v)}> <Icon name='ios-close-circle-outline' size={28} color={linkColor} /> </TouchableOpacity> </View> } let { width } = utils.dimensions(component) item = <View style={{width: width - 40}}> <TouchableOpacity underlayColor='transparent' onPress={editItem.bind(this, prop, v)}> {item} </TouchableOpacity> {cancel} </View> } else if (cancelItem && !hadCancel) { hadCancel = true item = <TouchableOpacity underlayColor='transparent' onPress={cancelItem.bind(this, prop, v)}> <View style={styles.row}> {item} <View style={{position: 'absolute', top: 0, right: 7}}> <Icon name='ios-close-circle-outline' size={28} color={linkColor} /> </View> </View> </TouchableOpacity> } ret.push( <View key={this.getNextKey()}> {item} </View> ) }) if (!ret.length) { let vTitle = displayName || v.title || translate(utils.getModel(utils.getType(v))) let image = v.photo && <Image source={{uri: v.photo}} style={styles.thumb} /> let color = cancelItem ? '#757575' : linkColor let item = <View style={{flexDirection: 'row', paddingVertical: 7}}> {image} <Text style={[styles.itemText, {color}]}>{vTitle}</Text> </View> if (cancelItem) { item = <TouchableOpacity underlayColor='transparent' key={this.getNextKey()} onPress={cancelItem.bind(this, prop, v)}> <View style={styles.row}> {item} <Icon name='md-close' size={20} color={linkColor} style={{marginTop: 12}} /> </View> </TouchableOpacity> } else { let isMessageView if (resource._message) isMessageView = true else isMessageView = (ref !== ORGANIZATION && ref !== PROFILE) let componentName = isMessageView && MESSAGE_VIEW || RESOURCE_VIEW item = <TouchableOpacity underlayColor='transparent' key={this.getNextKey()} onPress={() => { navigator.push({ title: vTitle, componentName, backButtonTitle: 'Back', passProps: {resource: v, bankStyle, currency, locale} }) }}> {item} </TouchableOpacity> } ret.push(item) } let sep = counter !== cnt && <View style={styles.itemSeparator}></View> return ( <View key={this.getNextKey()} style={styles.item} > {ret} {sep} </View> ) }); }, showPDF({photo}) { const { bankStyle, navigator } = this.props navigator.push({ backButtonTitle: 'Back', title: photo.name || translate('Document'), componentName: 'ArticleView', passProps: { href: photo.url, bankStyle }, // sceneConfig: Navigator.SceneConfigs.FadeAndroid, }) }, renderItem({editItem, cancelItem, prop, v}) { const { bankStyle } = this.props let linkColor = (bankStyle && bankStyle.linkColor) || defaultBankStyle.linkColor if (editItem) { return <View> <TouchableOpacity underlayColor='transparent' onPress={editItem.bind(this, prop, v)}> <View style={styles.itemContent}> <Text style={styles.itemHighlightTitle}>{utils.getDisplayName({resource: v})}</Text> </View> </TouchableOpacity> <View style={styles.cancelIcon}> <TouchableOpacity underlayColor='transparent' onPress={cancelItem.bind(this, prop, v)}> <Icon name='ios-close-circle-outline' size={28} color={linkColor} /> </TouchableOpacity> </View> </View> } else { return <View> <TouchableOpacity underlayColor='transparent' onPress={this.showRefResource.bind(this, v, prop)}> <View style={styles.itemContent}> <Text style={styles.itemHighlightTitle}>{utils.getDisplayName({resource: v})}</Text> </View> </TouchableOpacity> </View> } }, renderSimpleProp({val, pMeta, modelName, component, hasGroups, showResourceProperty}) { let { bankStyle } = this.props if (Array.isArray(val)) return this.renderSimpleArrayProp({val, pMeta, modelName, component, showResourceProperty}) let { units } = pMeta if (units === '%') val += units else if (units && units.charAt(0) != '[') val += ' ' + units let isSmallScreen = utils.isSmallScreen(component) let descStyle = /*hasGroups && !isSmallScreen ? styles.descriptionGroup :*/ styles.description if (val === NOT_SPECIFIED) return <Text style={[descStyle, {color: bankStyle.linkColor}]}>{val}</Text> if (typeof val === 'number') return <Text style={descStyle}>{val}</Text>; if (typeof val === 'boolean') val = <Text style={descStyle}>{val ? 'Yes' : 'No'}</Text>; if (pMeta.signature) { let { width } = utils.dimensions(component) let h = 200 let w = width - 40 return <View style={styles.container}> <Image style={{maxWidth: w, height: h}} source={{uri: val}} resizeMode='contain'/> </View> } if (typeof val === 'string' && pMeta.type !== 'object' && (val.indexOf('http://') == 0 || val.indexOf('https://') === 0)) return <Text onPress={this.onPress.bind(this, val)} style={[styles.description, {color: bankStyle.textColor}]}>{val}</Text>; // else if (modelName === TERMS_AND_CONDITIONS) { // val = <Text style={[styles.description, {flexWrap: 'wrap'}]}>{val}</Text>; if (pMeta.markdown) { return <View style={styles.container}> <Markdown markdownStyles={uiUtils.getMarkdownStyles(bankStyle)}> {val} </Markdown> </View> } if (pMeta.range === 'model') val = translate(utils.getModel(val)) else if (pMeta.range === 'password') val = '*********' return <Text style={descStyle}>{val}</Text>; }, generateCopyLinkButton(resource) { const { linkColor } = this.props.bankStyle // if (params && params.isIcon) { let paddingRight = utils.isAndroid() ? 0 : 10 let style = { borderColor: linkColor, borderWidth: 1, opacity: 0.5 } return <TouchableOpacity onPress={this.copy.bind(this, resource)} style={{paddingRight}}> <View style={[buttonStyles.treeButton, style]}> <Icon name='ios-copy-outline' size={30} color={linkColor} style={styles.conversationsIcon} /> </View> </TouchableOpacity> // } // return <TouchableOpacity onPress={this.copy.bind(this)} style={styles.copyView}> // <View style={[styles.copyButton, {borderColor: linkColor}]}> // <View style={styles.copyIcon}> // <Icon name='ios-copy-outline' color={linkColor} size={30}/> // </View> // <Text style={[styles.copyText, {color: linkColor}]}>{translate('createResourceLink')}</Text> // </View> // </TouchableOpacity> }, copy(resource) { Actions.getResourceLink({resource}) }, renderCopyLinkActionSheet(resource) { let buttons = [{ text: translate('createResourceLink'), onPress: () => this.copy(resource) }, { text: translate('cancel') } ] return ( <ActionSheet ref={(o) => { this.ActionSheet = o }} options={buttons} /> ) }, renderMenu(component) { let { modelName, bankStyle } = this.props let isAndroid = utils.isAndroid() const icon = isAndroid ? 'md-menu' : 'md-more' const color = isAndroid ? bankStyle.menuBgColor : bankStyle.menuColor const backgroundColor = isAndroid ? '#ffffff' : bankStyle.menuBgColor let width = utils.dimensions(component).width return ( <View style={[styles.footer, {width}]}> <TouchableOpacity onPress={() => this.ActionSheet.show()}> <View style={[buttonStyles.menuButton, {opacity: 0.4, backgroundColor}]}> <Icon name={icon} size={33} color={color}/> </View> </TouchableOpacity> </View> ) }, renderSimpleArrayProp({val, pMeta, modelName, component, showResourceProperty}) { if (pMeta.items.backlink) return <View key={this.getNextKey()} /> if (pMeta.grid) return this.renderSimpleGrid(val, pMeta, component) let vCols = pMeta.viewCols; if (!vCols) vCols = pMeta.items.ref && utils.getModel(pMeta.items.ref).viewCols let items = this.renderItems({value: val, prop: pMeta, component, showResourceProperty}) const model = utils.getModel(modelName) let hasFormItems = this.hasItemsWithFormRefs(model) val = hasFormItems || items.length < 2 ? items : this.renderItemsGroups({groups: items, component}) val = <View style={{marginHorizontal: 7}}>{val}</View> let title = pMeta.title || utils.makeLabel(pMeta.name) let titleEl if (!pMeta.skipLabel) titleEl = <Text style={styles.titleEl}>{title}</Text> let icon let cnt = val.length; if (cnt > 3 && modelName !== TERMS_AND_CONDITIONS) icon = <Icon name={'ios-arrow-down'} size={15} color='#7AAAC3' style={{position: 'absolute', right: 10, top: 10}}/> let header = <View style={styles.justRow}> {titleEl} {icon} </View> let separator = <View style={styles.separator}></View>; if (cnt > 3) return <View key={this.getNextKey()}> {separator} <Accordion sections={[title]} header={header} content={val} underlayColor='transparent' easing='easeIn' /> </View> else return <View key={this.getNextKey()}> {titleEl} {val} </View> }, hasItemsWithFormRefs(model) { const itemProps = utils.getPropertiesWithAnnotation(model, 'items') for (let p in itemProps) { const prop = itemProps[p] if (!prop.items.ref || !prop.inlined) continue const m = utils.getModel(prop.items.ref) if (utils.isSubclassOf(m, FORM)) return true const { properties:mProps } = m for (let p in mProps) { const mProp = mProps[p] if (mProp.inlined && mProp.ref && utils.isSubclassOf(utils.getModel(mProp.ref))) return true } } return false }, renderItemsGroups({groups, component}) { const { bankStyle } = this.props let prettyGroups = [] let isSmallScreen = utils.isSmallScreen(component) if (isSmallScreen) { for (let i=0; i<groups.length; i++) { prettyGroups.push(<View style={styles.prettyGroup}> <View style={{padding: 5, flex: 1}}> {groups[i]} </View> </View>) } return prettyGroups } for (let i=0; i<groups.length; i+=2) { let group1 = groups[i] let group2 = (i === groups.length-1) ? <View/> : groups[i + 1] prettyGroups.push(<View style={styles.prettyGroup}> <View style={styles.row}> <View style={styles.leftGroup}> {group1} </View> <View style={styles.rightGroup}> {group2} </View> </View> </View>) } return prettyGroups }, renderSimpleGrid(value, prop, component) { if (!value || prop.items.backlink) return <View key={this.getNextKey()} /> let { navigator, locale, currency, bankStyle } = this.props const modelName = prop.items.ref let gridCols = uiUtils.getGridCols(modelName) if (!gridCols) return let header = <GridHeader gridCols={gridCols} modelName={modelName} navigator={navigator}/> let rows = [] for (let i=0; i<value.length; i++) { rows.push( <GridRow key={'_' + prop.name} isSmallScreen={false} modelName={modelName} navigator={navigator} currency={currency} locale={locale} gridCols={gridCols} resource={value[i]} bankStyle={bankStyle} /> ); } return <View> {header} {rows} </View> }, showJson(params) { let { json, indent, isView } = params _.extend(params, {rawStyles: createStyles({bankStyle: this.props.bankStyle, indent, isView})}) if (!Array.isArray(json)) return this.showJsonPart(params) return json.map((r) => { let p = _.cloneDeep(params) p.json = r p.jsonRows = [] return this.showJsonPart(p) }) }, showJsonPart(params) { let {prop, json, isView, jsonRows, skipLabels, indent, isOnfido, isBreakdown, rawStyles} = params let { resource, bankStyle } = this.props bankStyle = bankStyle || defaultBankStyle let rType = resource[TYPE] let hideGroup = prop && hideGroupInJSON[rType] let showCollapsed = showCollapsedMap && showCollapsedMap[rType] skipLabels = !skipLabels && prop && skipLabelsInJSON[rType] && skipLabelsInJSON[rType][prop] let backgroundColor = isView ? bankStyle.linkColor : bankStyle.verifiedHeaderColor let color = isView ? '#ffffff' : bankStyle.verifiedHeaderTextColor let backlinksBg = {backgroundColor, flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 10, marginHorizontal: isView ? 0 : -10} if (prop) { let cols = [] let state let icon if (showCollapsed && showCollapsed === prop.name) icon = <Icon size={20} name='ios-arrow-down' color='#ffffff' style={styles.arrow} /> if (isOnfido) { let color = json.result === 'clear' ? '#f1ffe7' : 'red' cols.push(<Col sm={1} md={1} lg={1} style={{paddingVertical: 5, backgroundColor}} key={this.getNextKey()}> <Text style={[styles.bigTitle, {color: color, alignSelf: 'center'}]}>{json.result}</Text> {icon} </Col>) } let style = {opacity: 0.7, ...backlinksBg} let colSize = cols.length && 2 || 3 cols.push(<Col sm={colSize} md={colSize} lg={colSize} style={style} key={this.getNextKey()}> <Text style={[styles.hugeTitle, {color, paddingVertical: 10}]}>{translate(prop)}</Text> {!isOnfido && icon} </Col>) jsonRows.push(<Row size={3} style={styles.gridRow} key={this.getNextKey()} nowrap> {cols} </Row>) } if (!indent) indent = 0 let textStyle = indent === 1 || !isBreakdown ? styles.bigTitle : styles.title if (prop || !isBreakdown) { for (let p in json) { let jVal = json[p] if (typeof jVal === 'object' || p === 'result') continue let label if (!skipLabels || skipLabels.indexOf(p) === -1) label = <Text style={[styles.title, {flex: 1, paddingLeft: 10}]}>{utils.makeLabel(p)}</Text> let val jVal += '' if (jVal.indexOf('http://') === 0 || jVal.indexOf('https://') === 0) val = <Text style={[styles.title, {flex: 1, color: bankStyle.linkColor}]} onPress={() => Linking.openURL(jVal)}>{jVal}</Text> else val = <Text style={[styles.title, {flex: 1, color: '#555555'}]}>{jVal}</Text> jsonRows.push(<Row size={3} style={styles.gridRow} key={this.getNextKey()} nowrap> <Col sm={1} md={1} lg={1} style={rawStyles.col} key={this.getNextKey()}> {label} </Col> <Col sm={2} md={2} lg={2} style={styles.rowStyle} key={this.getNextKey()}> {val} </Col> </Row>) } } else if (isOnfido && !indent) { jsonRows.push(<Row size={3} style={styles.gridRow} key={this.getNextKey()} nowrap> <Col sm={3} md={3} lg={3} style={styles.rowStyle} key={this.getNextKey()}> <Text style={[styles.bigTitle, {color: color, paddingVertical: 10}]}>{translate('Breakdown')}</Text> </Col> </Row>) } for (let p in json) { if (isOnfido) { if (isBreakdown && p === 'result') continue if (p === 'properties') continue } if (prop && hideGroup && hideGroup.indexOf(p) !== -1) continue let jVal = json[p] if (typeof jVal !== 'object') continue if (utils.isEmpty(jVal) || this.checkIfJsonEmpty(jVal)) continue if (Array.isArray(jVal)) { let arrRows = [] jVal.forEach((js) => { if (typeof js === 'object') { this.showJson({json: js, isView, jsonRows: arrRows, indent: indent + 1}) jsonRows.push(<Row size={3} style={styles.rowStyle} key={this.getNextKey()}> <Col sm={3} md={3} lg={3} style={rawStyles.col} key={this.getNextKey()}> <Text style={[styles.bigTitle, {flex: 1, paddingLeft: 10}]}>{utils.makeLabel(p)}</Text> </Col> </Row>) jsonRows.push(arrRows) } else { jsonRows.push(<Row size={3} style={styles.rowStyle} key={this.getNextKey()}> <Col sm={1} md={1} lg={1} style={rawStyles.col} key={this.getNextKey()}> <Text style={[styles.title, styles.textContainer]}>{utils.makeLabel(p)}</Text> </Col> <Col sm={2} md={2} lg={2} style={styles.rowStyle} key={this.getNextKey()}> <Text style={[styles.title, {flex: 1, color: '#555555'}]}>{js + ''}</Text> </Col> </Row>) } }) continue } // HACK for Onfido let arrow if (showCollapsed && showCollapsed === p) arrow = <Icon color={bankStyle.linkColor} size={20} name={'ios-arrow-down'} style={{marginRight: 10, marginTop: 7}}/> // HACK for Onfido if (p !== 'breakdown') { let result if (isOnfido && isBreakdown) { let color = isBreakdown && jVal.properties ? {color: '#757575'} : {color: jVal.result === 'clear' ? 'green' : 'red'} result = <Text style={[textStyle, color]}>{jVal.result}</Text> } if (result || arrow) { jsonRows.push(<Row size={3} style={styles.row} key={this.getNextKey()}> <Col sm={1} md={1} lg={1} style={rawStyles.col} key={this.getNextKey()}> <Text style={textStyle}>{utils.makeLabel(p)}</Text> </Col> <Col sm={2} md={2} lg={2} style={styles.col} key={this.getNextKey()}> {result} {arrow} </Col> </Row>) } else { jsonRows.push(<Row size={3} style={styles.row} key={this.getNextKey()}> <Col sm={3} md={3} lg={3} style={rawStyles.col} key={this.getNextKey()}> <Text style={[textStyle, {paddingLeft: 10}]}>{utils.makeLabel(p)}</Text> </Col> </Row>) } if (isBreakdown && jVal.properties) continue } else if (isOnfido) isBreakdown = true let params = {json: jVal, isView, jsonRows, skipLabels, indent: indent + 1, isOnfido, isBreakdown} this.showJson(params) } if (!prop) return if (showCollapsed && showCollapsed == prop.name) { let [header, ...content] = jsonRows return <Accordion key={this.getNextKey()} sections={[utils.makeLabel(showCollapsed)]} header={header} content={content} underlayColor='transparent' easing='easeOutQuad' /> } return jsonRows }, checkIfJsonEmpty(json) { for (let p in json) { if (!json[p]) continue if (typeof json[p] !== 'object') return false if (!this.checkIfJsonEmpty(json[p])) return false } return true }, showLoading(params) { return uiUtils.showLoading(params) }, addDataSecurity(resource) { let { txId, blockchain, networkName } = resource let { bankStyle, onPageLayout } = this.props let content let lstyles = createStyles({bankStyle}) let header = (<View style={{padding: 10}} key={this.getNextKey()}> <View style={{ flex: 1, flexDirection: 'row', paddingVertical: 5, paddingLeft: 10}}> <View style={lstyles.accent}/> <Text style={lstyles.dividerText}>{translate('dataSecurity')}</Text> </View> </View>) if (blockchain === 'corda') { let description = 'You\'ll be able to verify this transaction when you launch your Corda node.' content = <View style={{paddingHorizontal: 10}}> <View style={{flexDirection: 'row', paddingVertical: 3}}> <Text style={styles.dsTitle}>Blockchain: </Text> <Text style={styles.dsValue}>{blockchain}</Text> </View> <View style={styles.justRow}> <Text style={styles.dsTitle}>Network: </Text> <Text style={styles.dsValue}>{networkName}</Text> </View> <View> <Text style={styles.title}>TxID: </Text> <Text style={styles.dsValue}>{txId}</Text> </View> <Text style={[styles.content, {marginTop: 20}]}>{description}</Text> </View> } else { const description = 'This app uses blockchain technology to ensure you can always prove the contents of your data and whom you shared it with.' const urls = utils.getBlockchainExplorerUrlsForTx({ blockchain, networkName, txId }) if (urls.length) { const renderRow = (url, i) => { url = url.replace('$TXID', txId) return this.getBlockchainExplorerRow(url, i, styles) } const txs = <View>{urls.map(renderRow)}</View> content = <View style={{paddingHorizontal: 10}}> <TouchableOpacity onPress={this.onPress.bind(this, 'http://thefinanser.com/2016/03/the-best-blockchain-white-papers-march-2016-part-2.html/')}> <Text style={styles.content}>{description}</Text> </TouchableOpacity> {txs} </View> } } return <View> {header} {content} </View> }, getBlockchainExplorerRow(url, i, styles) { const { bankStyle } = this.props let key = `url${i}` return ( <TouchableOpacity onPress={this.onPress.bind(this, url)} key={key}> <Text style={[styles.description, {color: bankStyle.linkColor}]}>{translate('independentBlockchainViewer') + ' ' + (i+1)}</Text> </TouchableOpacity> ) }, showTreeNode({stub, prop, openChat}) { let {id, title} = stub debugger const { bankStyle, navigator, resource, currency, locale } = this.props let type = utils.getType(id) let isApplication = type === APPLICATION if (isApplication) { if (resource.from) title = `${title} -- ${resource.from.title} -> ${title}` } else title = `${title} -- ${utils.makeModelTitle(type)}` if (isApplication && openChat) { Actions.openApplicationChat(stub) return } let r if (resource && id === utils.getId(resource)) r = resource else r = { id } navigator.push({ componentName: isApplication ? APPLICATION_VIEW : MESSAGE_VIEW, backButtonTitle: 'Back', title, passProps: { bankStyle, resource: r, currency, locale } }) }, openApplicationChat(resource) { let { navigator, bankStyle, locale } = this.props let { wasFilledByEmployee } = this.state // let { bankStyle } = this.state // let resource = this.state.resource || this.props.resource let me = utils.getMe() let title let name = resource.applicantName || resource.applicant.title if (name) title = name + ' → ' + me.organization.title else title = me.organization.title let style = resource.style ? this.mergeStyle(resource.style) : bankStyle let route = { componentName: 'MessageList', backButtonTitle: 'Back', title: title, passProps: { resource: resource._context, filter: '', search: true, modelName: MESSAGE, application: resource, currency: resource.currency, wasFilledByEmployee, locale, bankStyle: style, } } navigator.push(route) }, } var createStyles = utils.styleFactory(component || PhotoList, function ({ dimensions, bankStyle, indent, isView }) { indent = indent || 0 return StyleSheet.create({ learnMore: { color: bankStyle.linkColor, paddingHorizontal: 7 }, bigTitle: { fontSize: 20, // fontFamily: 'Avenir Next', color: bankStyle.linkColor, marginTop: 3, marginBottom: 0, marginHorizontal: 7 }, col: { paddingVertical: 5, paddingRight: 10, paddingLeft: isView ? 10 * (indent + 1) : 10 * (indent - 1) }, accent: { width: 12, borderLeftColor: bankStyle.accentColor || 'orange', borderLeftWidth: 5, }, dividerText: { marginBottom: 5, fontSize: 26, fontWeight: '500', color: bankStyle.linkColor, fontFamily: bankStyle.headerFont }, }) }) var styles = StyleSheet.create({ justRow: { flexDirection: 'row' }, textContainer: { // width: 30 flex: 1 }, container: { margin: 10, flex: 1 }, thumb: { width: 25, height: 25, marginRight: 2, borderRadius: 5 }, itemText: { fontSize: 16, marginBottom: 0, // marginHorizontal: 7, color: '#757575', }, itemHighlight: { fontSize: 16, marginBottom: 0, marginRight: 5, // marginHorizontal: 7, fontWeight: '600', color: '#555555', }, itemHighlightTitle: { fontSize: 16, marginBottom: 0, marginRight: 5, // marginHorizontal: 7, color: '#555555', }, itemSeparator: { height: 1, marginTop: 5, // backgroundColor: '#eeeeee', // marginHorizontal: 15 }, separator: { height: 1, marginTop: 5, marginBottom: 10, marginHorizontal: -10, alignSelf: 'stretch', backgroundColor: '#eeeeee' }, item: { paddingTop: 7, }, row: { flexDirection: 'row', justifyContent: 'space-between', // marginRight: 3 }, title: { fontSize: 16, marginTop: 3, marginBottom: 0, marginHorizontal: 7, color: '#9b9b9b' }, titleEl: { fontSize: 16, marginTop: 3, marginBottom: 0, marginHorizontal: 7, color: '#9b9b9b' }, arrow: { position: 'absolute', top: 15, right: 20 }, description: { fontSize: 18, marginVertical: 3, marginHorizontal: 7, color: '#555555', }, descriptionGroup: { fontSize: 18, width: '45%', marginVertical: 3, marginHorizontal: 7, color: '#555555', }, hugeTitle: { fontSize: 24, // fontFamily: 'Avenir Next', // marginTop: 3, marginBottom: 0, marginHorizontal: 7 }, bigTitle: { fontSize: 20, // fontFamily: 'Avenir Next', // color: '#7AAAC3', marginTop: 3, marginBottom: 0, marginHorizontal: 7 }, dsTitle: { width: 90, fontSize: 16, // fontFamily: 'Avenir Next', marginTop: 3, marginBottom: 0, marginHorizontal: 7, color: '#9b9b9b' }, dsValue: { fontSize: 18, marginHorizontal: 7, color: '#555555', }, content: { color: '#9b9b9b', fontSize: 16, marginHorizontal: 7, paddingBottom: 10 }, gridRow: { borderBottomColor: '#f5f5f5', paddingVertical: 5, // paddingRight: 7, borderBottomWidth: 1 }, itemContent: { // flex: 9, flex: 1, flexDirection: utils.isWeb() && 'row' || 'column', justifyContent: 'space-between' }, enumValue: { flexDirection: 'column', alignItems: 'flex-end' }, cancelIcon: { position: 'absolute', top: 0, right: 0 }, prettyGroup: { marginVertical: 10, marginRight: 10, backgroundColor: '#ffffff', borderColor: '#eeeeee', borderRadius: 15, borderWidth: 1, paddingVertical: 10 }, leftGroup: { padding: 5, flex: 1, borderRightColor:'#cccccc', borderRightWidth: 1 }, rightGroup: { padding: 5, flex: 1, width:'50%' }, copyView: { position: 'absolute', right: 20, bottom: 20, }, copyButton: { backgroundColor: '#ffffff', flexDirection: 'row', justifyContent: 'center', // width: 350, marginTop: 20, // alignSelf: 'center', paddingHorizontal: 20, height: 50, borderRadius: 15, borderWidth: 1, }, // copyText: { // fontSize: 20, // alignSelf: 'center' // }, // copyIcon: { // justifyContent: 'center', // paddingRight: 5 // }, footer: { flexDirection: 'row', // flexWrap: 'nowrap', justifyContent: 'flex-end', // height: 45, paddingHorizontal: 10, paddingBottom: 20, backgroundColor: 'transparent', // borderColor: '#eeeeee', // borderTopWidth: StyleSheet.hairlineWidth, // borderTopColor: '#cccccc', }, }) module.exports = ResourceMixin; // showJson(params) { // let { json, prop, isView } = params // let { resource, bankStyle } = this.props // const theme = { // scheme: 'custom', // base00: '#ffffff', // background // base01: '#272935', // base02: '#3a4055', // base03: '#5a647e', // base04: '#d4cfc9', // base05: '#e6e1dc', // base06: '#f4f1ed', // base07: '#f9f7f3', // base08: '#da4939', // base09: bankStyle.confirmationColor, // number // base0A: '#ffc66d', // base0B: bankStyle.linkColor, // string // base0C: '#519f50', // base0D: '#757575', // label // base0E: '#b6b3eb', // base0F: '#bc9458' // }; // json = utils.sanitize(json) // let backgroundColor = isView ? bankStyle.linkColor : bankStyle.verifiedHeaderColor // let color = isView ? '#ffffff' : bankStyle.verifiedHeaderTextColor // let style = {opacity: 0.7, backgroundColor, flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 10, marginHorizontal: isView ? 0 : -10, marginBottom: 10} // let icon // const rType = resource[TYPE] // const showCollapsed = showCollapsedMap && showCollapsedMap[rType] // // if (showCollapsed && showCollapsed === prop.name) // // icon = <Icon size={20} name='ios-arrow-down' color='#ffffff' style={styles.arrow} /> // let header = <TouchableOpacity onPress={() => { // this.state.hidden ? this.setState({hidden: false}) : this.setState({hidden: true}) // }} style={style} key={this.getNextKey()}> // <Text style={[styles.hugeTitle, {color, paddingVertical: 10}]}>{translate(prop)}</Text> // {icon} // </TouchableOpacity> // let content = ( // <View ref='json'> // <JSONTree data={json} invertTheme={false} hideRoot={true} theme={{ // extend: theme, // nestedNodeItemString: ({ style }, nodeType, expanded) => ({ // style: { // ...style, // fontSize: 18 // } // }) // }} // shouldExpandNode = {(keyName, data, level) => { // if (!keyName.length) // return this.state.hidden && false || true // else // return false // }} // getItemString={(type, data, itemType, itemString) => { // if (type === 'Array') // return <Text style={{fontSize: 16}}>{itemType} {itemString}</Text> // if (type === 'Object') // return // return <Text style={{fontSize: 16}}>{itemType} {itemString}</Text> // }} // labelRenderer={(raw, nodeType, expanded, hasItems) => { // const isArray = nodeType === 'Array' // // if (isArray && !hasItems) { // // return <View style={{height: 0}} /> // const isObject = nodeType === 'Object' // let val = isObject && raw[0] || `${raw[0]}:` // return <Text style={{ padding: 15, paddingLeft: (isObject || isArray) && 7 || 15, fontSize: 16 }}>{val}</Text> // }} // valueRenderer={raw => { // if (typeof raw === 'string') // raw = raw.replace(/['"]+/g, '') // return <Text style={{ padding: 15, fontSize: 16 }}>{raw}</Text> // }} // /> // </View> // ) // return <View> // {header} // {content} // </View> // },
docs/app/Examples/elements/Image/States/ImageExampleDisabled.js
koenvg/Semantic-UI-React
import React from 'react' import { Image } from 'semantic-ui-react' const ImageExampleDisabled = () => ( <Image src='/assets/images/wireframe/image.png' size='medium' disabled /> ) export default ImageExampleDisabled
packages/storybook/stories/tab.js
xcv58/Tab-Manager-v2
import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import Tab from 'components/Tab/Tab' import DraggableTab from 'components/Tab/DraggableTab' import Icon from 'components/Tab/Icon' import store from '../.storybook/mock-store' store.windowStore.getAllWindows() const tabs = store.windowStore.windows[0].tabs const tabProps = (props) => { const tab = tabs[Math.floor(Math.random() * tabs.length)] Object.assign(tab, props) return { tab, dragPreview: action('dragPreview'), getWindowList: action('getWindowList'), faked: true, } } storiesOf('Tab', module) .add('DraggableTab', () => <DraggableTab {...tabProps({ pinned: false })} />) .add('Tab', () => <Tab {...tabProps({ pinned: false })} />) .add('Pinned DraggableTab', () => ( <DraggableTab {...tabProps({ pinned: true })} /> )) .add('Pinned Tab', () => <Tab {...tabProps({ pinned: true })} />) const iconStory = storiesOf('Icon', module) ;[ 'bookmarks', 'chrome', 'crashes', 'downloads', 'extensions', 'flags', 'history', 'settings', ].forEach((x) => { iconStory.add(`Chrome Icon ${x}`, () => ( <Icon {...tabProps()} url={`chrome://${x}`} /> )) })
packages/reactor-kitchensink/src/examples/FormFields/SearchField/SearchField.js
markbrocato/extjs-reactor
import React, { Component } from 'react'; import { Panel, Container, Button, SearchField, TitleBar } from '@extjs/ext-react' export default class SearchFieldExample extends Component { render() { return ( <Container width="600" layout="vbox" padding={20} platformConfig={{ phone: { width: '100%' } }} > <div style={styles.heading}>alt</div> <TitleBar title="TitleBar" maxWidth="600" margin="0 0 30 0"> <SearchField align="right" ui="alt" width="200" placeholder="Search" /> </TitleBar> <div style={styles.heading}>faded</div> <Container layout="vbox" padding="20 20" style={{backgroundColor: 'white'}} margin="0 0 30 0" shadow> <SearchField ui="faded" placeholder="Search" /> </Container> <div style={styles.heading}>solo</div> <Container layout="hbox" padding="20 20" style={{backgroundColor: '#F0F0F0'}} shadow> {/* @include textfield-ui( $ui: 'ks-search-right-trigger', $input-padding: 10px 10px 10px 15px, $input-padding-big: 7px 7px 7px 15px ); */} <SearchField ui="solo ks-search-right-trigger" shadow placeholder="Search" margin="0 10 0 0" triggerAlign="right" triggers={{ search: { type: 'search', side: 'right' } }} flex={1} /> <Button iconCls="x-fa fa-arrow-right" ui="action round raised" height={36} width={36} platformConfig={{ phone: { height: 40, width: 40 } }} /> </Container> </Container> ) } } const styles = { heading: { fontSize: '13px', fontFamily: 'Menlo, Courier', margin: '0 0 8px 0' } }
src/components/icons/EyeRegular.js
lmammino/loige.co
import React from 'react' const EyeRegular = props => ( <svg aria-hidden="true" data-prefix="far" data-icon="eye" className="svg-inline--fa fa-eye fa-w-18" viewBox="0 0 576 512" width="1em" height="1em" {...props} > <path fill="currentColor" d="M569.354 231.631C512.97 135.949 407.81 72 288 72 168.14 72 63.004 135.994 6.646 231.631a47.999 47.999 0 0 0 0 48.739C63.031 376.051 168.19 440 288 440c119.86 0 224.996-63.994 281.354-159.631a47.997 47.997 0 0 0 0-48.738zM288 392c-102.556 0-192.091-54.701-240-136 44.157-74.933 123.677-127.27 216.162-135.007C273.958 131.078 280 144.83 280 160c0 30.928-25.072 56-56 56s-56-25.072-56-56l.001-.042C157.794 179.043 152 200.844 152 224c0 75.111 60.889 136 136 136s136-60.889 136-136c0-31.031-10.4-59.629-27.895-82.515C451.704 164.638 498.009 205.106 528 256c-47.908 81.299-137.444 136-240 136z" /> </svg> ) export default EyeRegular
node_modules/material-ui/lib/svg-icons/action/assignment.js
Sporks/Doc-tor
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ActionAssignment = _react2.default.createClass({ displayName: 'ActionAssignment', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( _svgIcon2.default, this.props, _react2.default.createElement('path', { d: 'M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z' }) ); } }); exports.default = ActionAssignment; module.exports = exports['default'];
Week_12/SOAPClient/SOAPClient/Scripts/jquery-1.10.2.js
peteratseneca/dps907fall2015
/* NUGET: BEGIN LICENSE TEXT * * Microsoft grants you the right to use these script files for the sole * purpose of either: (i) interacting through your browser with the Microsoft * website or online service, subject to the applicable licensing or use * terms; or (ii) using the files as included with a Microsoft product subject * to that product's license terms. Microsoft reserves all other rights to the * files not expressly granted by Microsoft, whether by implication, estoppel * or otherwise. Insofar as a script file is dual licensed under GPL, * Microsoft neither took the code under GPL nor distributes it thereunder but * under the terms set out in this paragraph. All notices and licenses * below are for informational purposes only. * * NUGET: END LICENSE TEXT */ /*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { 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 && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_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 || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. 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; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // 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(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } 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#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( 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" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // 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 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? 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 #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 ) && 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]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, 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.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", 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 = 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><option selected=''></option></select>"; // 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: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (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 ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // 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 || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 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 ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; 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 ); } } 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 for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, 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[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( 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 only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; 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(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // 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 ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && 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; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); 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 (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; 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 action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // 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; // 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"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // 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; // 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>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var 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 ] = core_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 ( jQuery.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 throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which 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 ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // 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" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; 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 ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; 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( core_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 === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; 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 ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, 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 === core_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( core_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 ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "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; } } } }); // Hooks 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; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : 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) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, 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; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.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 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { 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 ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // 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 ( !jQuery.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 rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|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 !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_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( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // 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 && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( 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 = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* 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 ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, 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 ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = 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; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, 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; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { 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)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); 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 ); }; }); jQuery.extend({ 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; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, 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 ( isSimple.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; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, 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 ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { 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 jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && 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 ) { // Hope ajax is available... 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; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? 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 ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _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(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": 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": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.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 // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.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( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // 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 }); }; }); /* 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 }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var 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() ); } 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 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 ); } 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; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, 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 if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } 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; } } } } } 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.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // 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; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || 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 jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // 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. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
app/scripts/components/node-details/node-details-generic-table.js
hustbill/network-verification-ui
import React from 'react'; import sortBy from 'lodash/sortBy'; import { Map as makeMap } from 'immutable'; import { NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT } from '../../constants/limits'; import { isNumber, getTableColumnsStyles, genericTableEntryKey } from '../../utils/node-details-utils'; import NodeDetailsTableHeaders from './node-details-table-headers'; import MatchedText from '../matched-text'; import ShowMore from '../show-more'; function sortedRows(rows, columns, sortedBy, sortedDesc) { const column = columns.find(c => c.id === sortedBy); const sorted = sortBy(rows, (row) => { let value = row.entries[sortedBy]; if (isNumber(column)) { value = parseFloat(value); } return value; }); if (sortedDesc) { sorted.reverse(); } return sorted; } export default class NodeDetailsGenericTable extends React.Component { constructor(props, context) { super(props, context); this.state = { limit: NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT, sortedBy: props.columns && props.columns[0].id, sortedDesc: true }; this.handleLimitClick = this.handleLimitClick.bind(this); this.updateSorted = this.updateSorted.bind(this); } updateSorted(sortedBy, sortedDesc) { this.setState({ sortedBy, sortedDesc }); } handleLimitClick() { this.setState({ limit: this.state.limit ? 0 : NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT }); } render() { const { sortedBy, sortedDesc } = this.state; const { columns, matches = makeMap() } = this.props; const expanded = this.state.limit === 0; let rows = this.props.rows || []; let notShown = 0; // If there are rows that would be hidden behind 'show more', keep them // expanded if any of them match the search query; otherwise hide them. if (this.state.limit > 0 && rows.length > this.state.limit) { const hasHiddenMatch = rows.slice(this.state.limit).some(row => columns.some(column => matches.has(genericTableEntryKey(row, column))) ); if (!hasHiddenMatch) { notShown = rows.length - NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT; rows = rows.slice(0, this.state.limit); } } const styles = getTableColumnsStyles(columns); return ( <div className="node-details-generic-table"> <table> <thead> <NodeDetailsTableHeaders headers={columns} sortedBy={sortedBy} sortedDesc={sortedDesc} onClick={this.updateSorted} /> </thead> <tbody> {sortedRows(rows, columns, sortedBy, sortedDesc).map(row => ( <tr className="node-details-generic-table-row" key={row.id}> {columns.map((column, index) => { const match = matches.get(genericTableEntryKey(row, column)); const value = row.entries[column.id]; return ( <td className="node-details-generic-table-value truncate" title={value} key={column.id} style={styles[index]}> <MatchedText text={value} match={match} /> </td> ); })} </tr> ))} </tbody> </table> <ShowMore handleClick={this.handleLimitClick} collection={this.props.rows} expanded={expanded} notShown={notShown} /> </div> ); } }
ajax/libs/yui/3.14.0/event-custom-base/event-custom-base-coverage.js
jemmy655/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/event-custom-base/event-custom-base.js']) { __coverage__['build/event-custom-base/event-custom-base.js'] = {"path":"build/event-custom-base/event-custom-base.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":0,"167":0,"168":0,"169":0,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":0,"222":0,"223":0,"224":0,"225":0,"226":0,"227":0,"228":0,"229":0,"230":0,"231":0,"232":0,"233":0,"234":0,"235":0,"236":0,"237":0,"238":0,"239":0,"240":0,"241":0,"242":0,"243":0,"244":0,"245":0,"246":0,"247":0,"248":0,"249":0,"250":0,"251":0,"252":0,"253":0,"254":0,"255":0,"256":0,"257":0,"258":0,"259":0,"260":0,"261":0,"262":0,"263":0,"264":0,"265":0,"266":0,"267":0,"268":0,"269":0,"270":0,"271":0,"272":0,"273":0,"274":0,"275":0,"276":0,"277":0,"278":0,"279":0,"280":0,"281":0,"282":0,"283":0,"284":0,"285":0,"286":0,"287":0,"288":0,"289":0,"290":0,"291":0,"292":0,"293":0,"294":0,"295":0,"296":0,"297":0,"298":0,"299":0,"300":0,"301":0,"302":0,"303":0,"304":0,"305":0,"306":0,"307":0,"308":0,"309":0,"310":0,"311":0,"312":0,"313":0,"314":0,"315":0,"316":0,"317":0,"318":0,"319":0,"320":0,"321":0,"322":0,"323":0,"324":0,"325":0,"326":0,"327":0,"328":0,"329":0,"330":0,"331":0,"332":0,"333":0,"334":0,"335":0,"336":0,"337":0,"338":0,"339":0,"340":0,"341":0,"342":0,"343":0,"344":0,"345":0,"346":0,"347":0,"348":0,"349":0,"350":0,"351":0,"352":0,"353":0,"354":0,"355":0,"356":0,"357":0,"358":0,"359":0,"360":0,"361":0,"362":0,"363":0,"364":0,"365":0,"366":0,"367":0,"368":0,"369":0,"370":0,"371":0,"372":0,"373":0,"374":0,"375":0,"376":0,"377":0,"378":0,"379":0,"380":0,"381":0,"382":0,"383":0,"384":0,"385":0,"386":0,"387":0,"388":0,"389":0,"390":0,"391":0,"392":0,"393":0,"394":0,"395":0,"396":0,"397":0,"398":0,"399":0,"400":0,"401":0,"402":0,"403":0,"404":0,"405":0,"406":0,"407":0,"408":0,"409":0,"410":0,"411":0,"412":0,"413":0,"414":0,"415":0,"416":0,"417":0,"418":0,"419":0,"420":0,"421":0,"422":0,"423":0,"424":0,"425":0,"426":0,"427":0,"428":0,"429":0,"430":0,"431":0,"432":0,"433":0,"434":0,"435":0,"436":0,"437":0,"438":0,"439":0,"440":0,"441":0,"442":0,"443":0,"444":0,"445":0,"446":0,"447":0,"448":0,"449":0,"450":0,"451":0,"452":0,"453":0,"454":0,"455":0,"456":0,"457":0,"458":0,"459":0,"460":0,"461":0,"462":0,"463":0,"464":0,"465":0,"466":0,"467":0,"468":0,"469":0,"470":0,"471":0,"472":0,"473":0,"474":0,"475":0,"476":0,"477":0,"478":0,"479":0,"480":0,"481":0,"482":0,"483":0,"484":0,"485":0,"486":0,"487":0,"488":0,"489":0,"490":0,"491":0,"492":0,"493":0,"494":0,"495":0,"496":0,"497":0,"498":0,"499":0,"500":0,"501":0,"502":0,"503":0,"504":0,"505":0,"506":0,"507":0,"508":0,"509":0,"510":0,"511":0,"512":0,"513":0,"514":0,"515":0,"516":0,"517":0,"518":0,"519":0,"520":0,"521":0,"522":0,"523":0,"524":0,"525":0,"526":0,"527":0,"528":0,"529":0,"530":0,"531":0,"532":0,"533":0,"534":0,"535":0,"536":0,"537":0,"538":0,"539":0,"540":0,"541":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0,0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0],"52":[0,0],"53":[0,0,0],"54":[0,0],"55":[0,0],"56":[0,0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0],"62":[0,0],"63":[0,0],"64":[0,0],"65":[0,0],"66":[0,0],"67":[0,0],"68":[0,0],"69":[0,0],"70":[0,0],"71":[0,0],"72":[0,0],"73":[0,0],"74":[0,0],"75":[0,0],"76":[0,0],"77":[0,0],"78":[0,0],"79":[0,0],"80":[0,0],"81":[0,0],"82":[0,0],"83":[0,0],"84":[0,0],"85":[0,0],"86":[0,0],"87":[0,0],"88":[0,0,0],"89":[0,0],"90":[0,0],"91":[0,0],"92":[0,0],"93":[0,0],"94":[0,0],"95":[0,0],"96":[0,0],"97":[0,0],"98":[0,0],"99":[0,0],"100":[0,0],"101":[0,0],"102":[0,0],"103":[0,0],"104":[0,0],"105":[0,0],"106":[0,0],"107":[0,0,0],"108":[0,0],"109":[0,0],"110":[0,0],"111":[0,0],"112":[0,0],"113":[0,0],"114":[0,0],"115":[0,0],"116":[0,0],"117":[0,0],"118":[0,0],"119":[0,0],"120":[0,0],"121":[0,0],"122":[0,0],"123":[0,0],"124":[0,0],"125":[0,0],"126":[0,0],"127":[0,0],"128":[0,0],"129":[0,0],"130":[0,0],"131":[0,0,0],"132":[0,0],"133":[0,0],"134":[0,0],"135":[0,0],"136":[0,0],"137":[0,0],"138":[0,0],"139":[0,0],"140":[0,0],"141":[0,0],"142":[0,0],"143":[0,0],"144":[0,0],"145":[0,0],"146":[0,0],"147":[0,0],"148":[0,0],"149":[0,0],"150":[0,0],"151":[0,0],"152":[0,0],"153":[0,0],"154":[0,0],"155":[0,0],"156":[0,0],"157":[0,0],"158":[0,0],"159":[0,0],"160":[0,0],"161":[0,0],"162":[0,0],"163":[0,0],"164":[0,0],"165":[0,0],"166":[0,0],"167":[0,0,0],"168":[0,0],"169":[0,0],"170":[0,0],"171":[0,0],"172":[0,0,0,0],"173":[0,0],"174":[0,0],"175":[0,0],"176":[0,0],"177":[0,0],"178":[0,0],"179":[0,0],"180":[0,0,0,0],"181":[0,0],"182":[0,0],"183":[0,0],"184":[0,0],"185":[0,0],"186":[0,0],"187":[0,0,0,0,0],"188":[0,0],"189":[0,0],"190":[0,0],"191":[0,0],"192":[0,0],"193":[0,0],"194":[0,0],"195":[0,0],"196":[0,0],"197":[0,0],"198":[0,0],"199":[0,0],"200":[0,0,0,0,0],"201":[0,0],"202":[0,0],"203":[0,0],"204":[0,0],"205":[0,0],"206":[0,0],"207":[0,0],"208":[0,0],"209":[0,0],"210":[0,0],"211":[0,0,0,0],"212":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":29},"end":{"line":1,"column":48}}},"2":{"name":"(anonymous_2)","line":75,"loc":{"start":{"line":75,"column":12},"end":{"line":75,"column":38}}},"3":{"name":"(anonymous_3)","line":112,"loc":{"start":{"line":112,"column":11},"end":{"line":112,"column":37}}},"4":{"name":"(anonymous_4)","line":136,"loc":{"start":{"line":136,"column":13},"end":{"line":136,"column":42}}},"5":{"name":"(anonymous_5)","line":152,"loc":{"start":{"line":152,"column":23},"end":{"line":152,"column":34}}},"6":{"name":"(anonymous_6)","line":173,"loc":{"start":{"line":173,"column":12},"end":{"line":173,"column":29}}},"7":{"name":"(anonymous_7)","line":212,"loc":{"start":{"line":212,"column":12},"end":{"line":212,"column":31}}},"8":{"name":"(anonymous_8)","line":227,"loc":{"start":{"line":227,"column":31},"end":{"line":227,"column":56}}},"9":{"name":"(anonymous_9)","line":242,"loc":{"start":{"line":242,"column":30},"end":{"line":242,"column":45}}},"10":{"name":"(anonymous_10)","line":261,"loc":{"start":{"line":261,"column":27},"end":{"line":261,"column":39}}},"11":{"name":"(anonymous_11)","line":329,"loc":{"start":{"line":329,"column":15},"end":{"line":329,"column":38}}},"12":{"name":"(anonymous_12)","line":343,"loc":{"start":{"line":343,"column":17},"end":{"line":343,"column":42}}},"13":{"name":"(anonymous_13)","line":358,"loc":{"start":{"line":358,"column":10},"end":{"line":358,"column":32}}},"14":{"name":"(anonymous_14)","line":371,"loc":{"start":{"line":371,"column":13},"end":{"line":371,"column":27}}},"15":{"name":"(anonymous_15)","line":432,"loc":{"start":{"line":432,"column":17},"end":{"line":432,"column":36}}},"16":{"name":"(anonymous_16)","line":468,"loc":{"start":{"line":468,"column":16},"end":{"line":468,"column":41}}},"17":{"name":"(anonymous_17)","line":701,"loc":{"start":{"line":701,"column":13},"end":{"line":701,"column":28}}},"18":{"name":"(anonymous_18)","line":744,"loc":{"start":{"line":744,"column":13},"end":{"line":744,"column":28}}},"19":{"name":"(anonymous_19)","line":757,"loc":{"start":{"line":757,"column":13},"end":{"line":757,"column":24}}},"20":{"name":"(anonymous_20)","line":808,"loc":{"start":{"line":808,"column":17},"end":{"line":808,"column":36}}},"21":{"name":"(anonymous_21)","line":825,"loc":{"start":{"line":825,"column":9},"end":{"line":825,"column":43}}},"22":{"name":"(anonymous_22)","line":879,"loc":{"start":{"line":879,"column":15},"end":{"line":879,"column":37}}},"23":{"name":"(anonymous_23)","line":893,"loc":{"start":{"line":893,"column":8},"end":{"line":893,"column":30}}},"24":{"name":"(anonymous_24)","line":915,"loc":{"start":{"line":915,"column":11},"end":{"line":915,"column":33}}},"25":{"name":"(anonymous_25)","line":928,"loc":{"start":{"line":928,"column":12},"end":{"line":928,"column":34}}},"26":{"name":"(anonymous_26)","line":971,"loc":{"start":{"line":971,"column":17},"end":{"line":971,"column":28}}},"27":{"name":"(anonymous_27)","line":982,"loc":{"start":{"line":982,"column":13},"end":{"line":982,"column":35}}},"28":{"name":"(anonymous_28)","line":1002,"loc":{"start":{"line":1002,"column":9},"end":{"line":1002,"column":28}}},"29":{"name":"(anonymous_29)","line":1022,"loc":{"start":{"line":1022,"column":10},"end":{"line":1022,"column":21}}},"30":{"name":"(anonymous_30)","line":1044,"loc":{"start":{"line":1044,"column":11},"end":{"line":1044,"column":26}}},"31":{"name":"(anonymous_31)","line":1075,"loc":{"start":{"line":1075,"column":16},"end":{"line":1075,"column":31}}},"32":{"name":"(anonymous_32)","line":1090,"loc":{"start":{"line":1090,"column":17},"end":{"line":1090,"column":32}}},"33":{"name":"(anonymous_33)","line":1107,"loc":{"start":{"line":1107,"column":15},"end":{"line":1107,"column":40}}},"34":{"name":"(anonymous_34)","line":1133,"loc":{"start":{"line":1133,"column":16},"end":{"line":1133,"column":31}}},"35":{"name":"(anonymous_35)","line":1155,"loc":{"start":{"line":1155,"column":20},"end":{"line":1155,"column":31}}},"36":{"name":"(anonymous_36)","line":1164,"loc":{"start":{"line":1164,"column":15},"end":{"line":1164,"column":26}}},"37":{"name":"(anonymous_37)","line":1178,"loc":{"start":{"line":1178,"column":13},"end":{"line":1178,"column":34}}},"38":{"name":"(anonymous_38)","line":1222,"loc":{"start":{"line":1222,"column":15},"end":{"line":1222,"column":49}}},"39":{"name":"(anonymous_39)","line":1273,"loc":{"start":{"line":1273,"column":13},"end":{"line":1273,"column":35}}},"40":{"name":"(anonymous_40)","line":1314,"loc":{"start":{"line":1314,"column":12},"end":{"line":1314,"column":31}}},"41":{"name":"(anonymous_41)","line":1346,"loc":{"start":{"line":1346,"column":14},"end":{"line":1346,"column":36}}},"42":{"name":"(anonymous_42)","line":1354,"loc":{"start":{"line":1354,"column":14},"end":{"line":1354,"column":25}}},"43":{"name":"(anonymous_43)","line":1366,"loc":{"start":{"line":1366,"column":16},"end":{"line":1366,"column":35}}},"44":{"name":"(anonymous_44)","line":1386,"loc":{"start":{"line":1386,"column":11},"end":{"line":1386,"column":26}}},"45":{"name":"(anonymous_45)","line":1389,"loc":{"start":{"line":1389,"column":35},"end":{"line":1389,"column":47}}},"46":{"name":"(anonymous_46)","line":1400,"loc":{"start":{"line":1400,"column":12},"end":{"line":1400,"column":23}}},"47":{"name":"(anonymous_47)","line":1425,"loc":{"start":{"line":1425,"column":13},"end":{"line":1425,"column":28}}},"48":{"name":"(anonymous_48)","line":1460,"loc":{"start":{"line":1460,"column":25},"end":{"line":1460,"column":40}}},"49":{"name":"(anonymous_49)","line":1471,"loc":{"start":{"line":1471,"column":15},"end":{"line":1471,"column":35}}},"50":{"name":"(anonymous_50)","line":1487,"loc":{"start":{"line":1487,"column":26},"end":{"line":1487,"column":46}}},"51":{"name":"(anonymous_51)","line":1516,"loc":{"start":{"line":1516,"column":9},"end":{"line":1516,"column":24}}},"52":{"name":"(anonymous_52)","line":1564,"loc":{"start":{"line":1564,"column":10},"end":{"line":1564,"column":21}}},"53":{"name":"(anonymous_53)","line":1566,"loc":{"start":{"line":1566,"column":21},"end":{"line":1566,"column":36}}},"54":{"name":"(anonymous_54)","line":1586,"loc":{"start":{"line":1586,"column":15},"end":{"line":1586,"column":26}}},"55":{"name":"(anonymous_55)","line":1588,"loc":{"start":{"line":1588,"column":21},"end":{"line":1588,"column":36}}},"56":{"name":"(anonymous_56)","line":1612,"loc":{"start":{"line":1612,"column":15},"end":{"line":1612,"column":35}}},"57":{"name":"(anonymous_57)","line":1645,"loc":{"start":{"line":1645,"column":8},"end":{"line":1645,"column":36}}},"58":{"name":"(anonymous_58)","line":1677,"loc":{"start":{"line":1677,"column":25},"end":{"line":1677,"column":40}}},"59":{"name":"(anonymous_59)","line":1767,"loc":{"start":{"line":1767,"column":15},"end":{"line":1767,"column":26}}},"60":{"name":"(anonymous_60)","line":1787,"loc":{"start":{"line":1787,"column":12},"end":{"line":1787,"column":40}}},"61":{"name":"(anonymous_61)","line":1814,"loc":{"start":{"line":1814,"column":22},"end":{"line":1814,"column":50}}},"62":{"name":"(anonymous_62)","line":1889,"loc":{"start":{"line":1889,"column":17},"end":{"line":1889,"column":28}}},"63":{"name":"(anonymous_63)","line":1900,"loc":{"start":{"line":1900,"column":15},"end":{"line":1900,"column":30}}},"64":{"name":"(anonymous_64)","line":1912,"loc":{"start":{"line":1912,"column":20},"end":{"line":1912,"column":31}}},"65":{"name":"(anonymous_65)","line":1982,"loc":{"start":{"line":1982,"column":13},"end":{"line":1982,"column":34}}},"66":{"name":"(anonymous_66)","line":1997,"loc":{"start":{"line":1997,"column":25},"end":{"line":1997,"column":40}}},"67":{"name":"(anonymous_67)","line":2022,"loc":{"start":{"line":2022,"column":19},"end":{"line":2022,"column":34}}},"68":{"name":"(anonymous_68)","line":2046,"loc":{"start":{"line":2046,"column":15},"end":{"line":2046,"column":50}}},"69":{"name":"(anonymous_69)","line":2098,"loc":{"start":{"line":2098,"column":14},"end":{"line":2098,"column":43}}},"70":{"name":"(anonymous_70)","line":2146,"loc":{"start":{"line":2146,"column":10},"end":{"line":2146,"column":25}}},"71":{"name":"(anonymous_71)","line":2221,"loc":{"start":{"line":2221,"column":16},"end":{"line":2221,"column":35}}},"72":{"name":"(anonymous_72)","line":2246,"loc":{"start":{"line":2246,"column":14},"end":{"line":2246,"column":39}}},"73":{"name":"(anonymous_73)","line":2271,"loc":{"start":{"line":2271,"column":11},"end":{"line":2271,"column":30}}},"74":{"name":"(anonymous_74)","line":2309,"loc":{"start":{"line":2309,"column":12},"end":{"line":2309,"column":23}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":2460,"column":39}},"2":{"start":{"line":9,"column":0},"end":{"line":12,"column":2}},"3":{"start":{"line":29,"column":0},"end":{"line":178,"column":2}},"4":{"start":{"line":76,"column":8},"end":{"line":76,"column":22}},"5":{"start":{"line":77,"column":8},"end":{"line":80,"column":9}},"6":{"start":{"line":78,"column":12},"end":{"line":78,"column":60}},"7":{"start":{"line":79,"column":12},"end":{"line":79,"column":36}},"8":{"start":{"line":82,"column":8},"end":{"line":82,"column":52}},"9":{"start":{"line":113,"column":8},"end":{"line":113,"column":22}},"10":{"start":{"line":114,"column":8},"end":{"line":117,"column":9}},"11":{"start":{"line":115,"column":12},"end":{"line":115,"column":60}},"12":{"start":{"line":116,"column":12},"end":{"line":116,"column":36}},"13":{"start":{"line":119,"column":8},"end":{"line":119,"column":51}},"14":{"start":{"line":138,"column":8},"end":{"line":138,"column":38}},"15":{"start":{"line":140,"column":8},"end":{"line":143,"column":9}},"16":{"start":{"line":142,"column":12},"end":{"line":142,"column":29}},"17":{"start":{"line":145,"column":8},"end":{"line":145,"column":24}},"18":{"start":{"line":147,"column":8},"end":{"line":155,"column":9}},"19":{"start":{"line":149,"column":12},"end":{"line":149,"column":47}},"20":{"start":{"line":152,"column":12},"end":{"line":154,"column":14}},"21":{"start":{"line":153,"column":16},"end":{"line":153,"column":60}},"22":{"start":{"line":158,"column":8},"end":{"line":158,"column":37}},"23":{"start":{"line":161,"column":8},"end":{"line":161,"column":39}},"24":{"start":{"line":163,"column":8},"end":{"line":163,"column":46}},"25":{"start":{"line":174,"column":8},"end":{"line":176,"column":9}},"26":{"start":{"line":175,"column":12},"end":{"line":175,"column":28}},"27":{"start":{"line":180,"column":0},"end":{"line":180,"column":10}},"28":{"start":{"line":212,"column":0},"end":{"line":218,"column":2}},"29":{"start":{"line":213,"column":4},"end":{"line":213,"column":19}},"30":{"start":{"line":214,"column":4},"end":{"line":214,"column":26}},"31":{"start":{"line":215,"column":4},"end":{"line":215,"column":27}},"32":{"start":{"line":216,"column":4},"end":{"line":216,"column":21}},"33":{"start":{"line":217,"column":4},"end":{"line":217,"column":20}},"34":{"start":{"line":227,"column":0},"end":{"line":233,"column":2}},"35":{"start":{"line":228,"column":4},"end":{"line":232,"column":5}},"36":{"start":{"line":229,"column":8},"end":{"line":229,"column":29}},"37":{"start":{"line":231,"column":8},"end":{"line":231,"column":30}},"38":{"start":{"line":242,"column":0},"end":{"line":245,"column":2}},"39":{"start":{"line":243,"column":4},"end":{"line":243,"column":28}},"40":{"start":{"line":244,"column":4},"end":{"line":244,"column":27}},"41":{"start":{"line":261,"column":0},"end":{"line":314,"column":2}},"42":{"start":{"line":263,"column":4},"end":{"line":267,"column":26}},"43":{"start":{"line":270,"column":4},"end":{"line":287,"column":5}},"44":{"start":{"line":271,"column":8},"end":{"line":286,"column":9}},"45":{"start":{"line":272,"column":12},"end":{"line":272,"column":46}},"46":{"start":{"line":273,"column":12},"end":{"line":285,"column":13}},"47":{"start":{"line":274,"column":16},"end":{"line":284,"column":17}},"48":{"start":{"line":276,"column":24},"end":{"line":276,"column":42}},"49":{"start":{"line":278,"column":24},"end":{"line":278,"column":43}},"50":{"start":{"line":279,"column":24},"end":{"line":279,"column":30}},"51":{"start":{"line":281,"column":24},"end":{"line":281,"column":41}},"52":{"start":{"line":282,"column":24},"end":{"line":282,"column":30}},"53":{"start":{"line":290,"column":4},"end":{"line":292,"column":5}},"54":{"start":{"line":291,"column":8},"end":{"line":291,"column":48}},"55":{"start":{"line":294,"column":4},"end":{"line":294,"column":28}},"56":{"start":{"line":295,"column":4},"end":{"line":295,"column":27}},"57":{"start":{"line":298,"column":4},"end":{"line":311,"column":5}},"58":{"start":{"line":299,"column":8},"end":{"line":310,"column":9}},"59":{"start":{"line":300,"column":12},"end":{"line":300,"column":49}},"60":{"start":{"line":302,"column":12},"end":{"line":309,"column":13}},"61":{"start":{"line":303,"column":16},"end":{"line":303,"column":37}},"62":{"start":{"line":305,"column":19},"end":{"line":309,"column":13}},"63":{"start":{"line":306,"column":16},"end":{"line":306,"column":39}},"64":{"start":{"line":308,"column":16},"end":{"line":308,"column":39}},"65":{"start":{"line":313,"column":4},"end":{"line":313,"column":15}},"66":{"start":{"line":329,"column":0},"end":{"line":332,"column":2}},"67":{"start":{"line":330,"column":4},"end":{"line":330,"column":19}},"68":{"start":{"line":331,"column":4},"end":{"line":331,"column":27}},"69":{"start":{"line":343,"column":0},"end":{"line":346,"column":2}},"70":{"start":{"line":344,"column":4},"end":{"line":344,"column":19}},"71":{"start":{"line":345,"column":4},"end":{"line":345,"column":31}},"72":{"start":{"line":358,"column":0},"end":{"line":361,"column":2}},"73":{"start":{"line":359,"column":4},"end":{"line":359,"column":19}},"74":{"start":{"line":360,"column":4},"end":{"line":360,"column":25}},"75":{"start":{"line":371,"column":0},"end":{"line":373,"column":2}},"76":{"start":{"line":372,"column":4},"end":{"line":372,"column":19}},"77":{"start":{"line":385,"column":0},"end":{"line":385,"column":19}},"78":{"start":{"line":399,"column":0},"end":{"line":442,"column":6}},"79":{"start":{"line":433,"column":8},"end":{"line":433,"column":14}},"80":{"start":{"line":435,"column":8},"end":{"line":439,"column":9}},"81":{"start":{"line":436,"column":12},"end":{"line":438,"column":13}},"82":{"start":{"line":437,"column":16},"end":{"line":437,"column":28}},"83":{"start":{"line":441,"column":8},"end":{"line":441,"column":17}},"84":{"start":{"line":468,"column":0},"end":{"line":498,"column":2}},"85":{"start":{"line":470,"column":4},"end":{"line":470,"column":49}},"86":{"start":{"line":472,"column":4},"end":{"line":472,"column":23}},"87":{"start":{"line":474,"column":4},"end":{"line":474,"column":21}},"88":{"start":{"line":475,"column":4},"end":{"line":475,"column":54}},"89":{"start":{"line":477,"column":4},"end":{"line":493,"column":5}},"90":{"start":{"line":491,"column":8},"end":{"line":491,"column":30}},"91":{"start":{"line":492,"column":8},"end":{"line":492,"column":25}},"92":{"start":{"line":495,"column":4},"end":{"line":497,"column":5}},"93":{"start":{"line":496,"column":8},"end":{"line":496,"column":41}},"94":{"start":{"line":523,"column":0},"end":{"line":523,"column":41}},"95":{"start":{"line":525,"column":0},"end":{"line":525,"column":38}},"96":{"start":{"line":527,"column":0},"end":{"line":1212,"column":2}},"97":{"start":{"line":702,"column":8},"end":{"line":706,"column":31}},"98":{"start":{"line":708,"column":8},"end":{"line":710,"column":9}},"99":{"start":{"line":709,"column":12},"end":{"line":709,"column":28}},"100":{"start":{"line":712,"column":8},"end":{"line":714,"column":9}},"101":{"start":{"line":713,"column":12},"end":{"line":713,"column":30}},"102":{"start":{"line":716,"column":8},"end":{"line":727,"column":9}},"103":{"start":{"line":717,"column":12},"end":{"line":717,"column":36}},"104":{"start":{"line":718,"column":12},"end":{"line":718,"column":33}},"105":{"start":{"line":720,"column":12},"end":{"line":722,"column":13}},"106":{"start":{"line":721,"column":16},"end":{"line":721,"column":33}},"107":{"start":{"line":724,"column":12},"end":{"line":726,"column":13}},"108":{"start":{"line":725,"column":16},"end":{"line":725,"column":35}},"109":{"start":{"line":729,"column":8},"end":{"line":731,"column":9}},"110":{"start":{"line":730,"column":12},"end":{"line":730,"column":46}},"111":{"start":{"line":733,"column":8},"end":{"line":733,"column":23}},"112":{"start":{"line":745,"column":8},"end":{"line":745,"column":30}},"113":{"start":{"line":746,"column":8},"end":{"line":747,"column":50}},"114":{"start":{"line":748,"column":8},"end":{"line":748,"column":23}},"115":{"start":{"line":749,"column":8},"end":{"line":749,"column":51}},"116":{"start":{"line":759,"column":8},"end":{"line":763,"column":26}},"117":{"start":{"line":765,"column":8},"end":{"line":768,"column":9}},"118":{"start":{"line":766,"column":12},"end":{"line":766,"column":47}},"119":{"start":{"line":767,"column":12},"end":{"line":767,"column":44}},"120":{"start":{"line":770,"column":8},"end":{"line":782,"column":9}},"121":{"start":{"line":771,"column":12},"end":{"line":775,"column":13}},"122":{"start":{"line":772,"column":16},"end":{"line":772,"column":48}},"123":{"start":{"line":774,"column":16},"end":{"line":774,"column":44}},"124":{"start":{"line":777,"column":12},"end":{"line":781,"column":13}},"125":{"start":{"line":778,"column":16},"end":{"line":778,"column":37}},"126":{"start":{"line":780,"column":16},"end":{"line":780,"column":26}},"127":{"start":{"line":784,"column":8},"end":{"line":796,"column":9}},"128":{"start":{"line":785,"column":12},"end":{"line":789,"column":13}},"129":{"start":{"line":786,"column":16},"end":{"line":786,"column":54}},"130":{"start":{"line":788,"column":16},"end":{"line":788,"column":48}},"131":{"start":{"line":791,"column":12},"end":{"line":795,"column":13}},"132":{"start":{"line":792,"column":16},"end":{"line":792,"column":41}},"133":{"start":{"line":794,"column":16},"end":{"line":794,"column":28}},"134":{"start":{"line":798,"column":8},"end":{"line":798,"column":30}},"135":{"start":{"line":809,"column":8},"end":{"line":809,"column":35}},"136":{"start":{"line":828,"column":8},"end":{"line":829,"column":22}},"137":{"start":{"line":831,"column":8},"end":{"line":847,"column":9}},"138":{"start":{"line":833,"column":12},"end":{"line":833,"column":39}},"139":{"start":{"line":838,"column":12},"end":{"line":840,"column":13}},"140":{"start":{"line":839,"column":16},"end":{"line":839,"column":49}},"141":{"start":{"line":842,"column":12},"end":{"line":846,"column":13}},"142":{"start":{"line":843,"column":16},"end":{"line":843,"column":72}},"143":{"start":{"line":845,"column":16},"end":{"line":845,"column":43}},"144":{"start":{"line":849,"column":8},"end":{"line":859,"column":9}},"145":{"start":{"line":850,"column":12},"end":{"line":852,"column":13}},"146":{"start":{"line":851,"column":16},"end":{"line":851,"column":34}},"147":{"start":{"line":853,"column":12},"end":{"line":853,"column":33}},"148":{"start":{"line":855,"column":12},"end":{"line":857,"column":13}},"149":{"start":{"line":856,"column":16},"end":{"line":856,"column":39}},"150":{"start":{"line":858,"column":12},"end":{"line":858,"column":38}},"151":{"start":{"line":861,"column":8},"end":{"line":867,"column":9}},"152":{"start":{"line":862,"column":12},"end":{"line":866,"column":13}},"153":{"start":{"line":863,"column":16},"end":{"line":863,"column":38}},"154":{"start":{"line":865,"column":16},"end":{"line":865,"column":43}},"155":{"start":{"line":869,"column":8},"end":{"line":869,"column":42}},"156":{"start":{"line":880,"column":8},"end":{"line":880,"column":79}},"157":{"start":{"line":881,"column":8},"end":{"line":881,"column":46}},"158":{"start":{"line":894,"column":8},"end":{"line":894,"column":79}},"159":{"start":{"line":896,"column":8},"end":{"line":900,"column":9}},"160":{"start":{"line":897,"column":12},"end":{"line":899,"column":15}},"161":{"start":{"line":901,"column":8},"end":{"line":901,"column":46}},"162":{"start":{"line":916,"column":8},"end":{"line":916,"column":79}},"163":{"start":{"line":917,"column":8},"end":{"line":917,"column":47}},"164":{"start":{"line":930,"column":8},"end":{"line":932,"column":9}},"165":{"start":{"line":931,"column":12},"end":{"line":931,"column":31}},"166":{"start":{"line":934,"column":8},"end":{"line":937,"column":34}},"167":{"start":{"line":939,"column":8},"end":{"line":947,"column":9}},"168":{"start":{"line":940,"column":12},"end":{"line":946,"column":13}},"169":{"start":{"line":941,"column":16},"end":{"line":941,"column":28}},"170":{"start":{"line":942,"column":16},"end":{"line":945,"column":17}},"171":{"start":{"line":943,"column":20},"end":{"line":943,"column":45}},"172":{"start":{"line":944,"column":20},"end":{"line":944,"column":28}},"173":{"start":{"line":949,"column":8},"end":{"line":957,"column":9}},"174":{"start":{"line":950,"column":12},"end":{"line":956,"column":13}},"175":{"start":{"line":951,"column":16},"end":{"line":951,"column":30}},"176":{"start":{"line":952,"column":16},"end":{"line":955,"column":17}},"177":{"start":{"line":953,"column":20},"end":{"line":953,"column":47}},"178":{"start":{"line":954,"column":20},"end":{"line":954,"column":28}},"179":{"start":{"line":959,"column":8},"end":{"line":959,"column":21}},"180":{"start":{"line":972,"column":8},"end":{"line":972,"column":50}},"181":{"start":{"line":985,"column":8},"end":{"line":985,"column":16}},"182":{"start":{"line":987,"column":8},"end":{"line":987,"column":35}},"183":{"start":{"line":989,"column":8},"end":{"line":991,"column":9}},"184":{"start":{"line":990,"column":12},"end":{"line":990,"column":25}},"185":{"start":{"line":993,"column":8},"end":{"line":993,"column":20}},"186":{"start":{"line":1028,"column":8},"end":{"line":1028,"column":22}},"187":{"start":{"line":1029,"column":8},"end":{"line":1029,"column":41}},"188":{"start":{"line":1031,"column":8},"end":{"line":1031,"column":32}},"189":{"start":{"line":1046,"column":8},"end":{"line":1064,"column":9}},"190":{"start":{"line":1047,"column":12},"end":{"line":1047,"column":24}},"191":{"start":{"line":1053,"column":12},"end":{"line":1053,"column":30}},"192":{"start":{"line":1055,"column":12},"end":{"line":1057,"column":13}},"193":{"start":{"line":1056,"column":16},"end":{"line":1056,"column":38}},"194":{"start":{"line":1059,"column":12},"end":{"line":1063,"column":13}},"195":{"start":{"line":1060,"column":16},"end":{"line":1060,"column":46}},"196":{"start":{"line":1062,"column":16},"end":{"line":1062,"column":45}},"197":{"start":{"line":1076,"column":8},"end":{"line":1076,"column":25}},"198":{"start":{"line":1077,"column":8},"end":{"line":1077,"column":27}},"199":{"start":{"line":1078,"column":8},"end":{"line":1082,"column":9}},"200":{"start":{"line":1079,"column":12},"end":{"line":1079,"column":38}},"201":{"start":{"line":1080,"column":12},"end":{"line":1080,"column":42}},"202":{"start":{"line":1081,"column":12},"end":{"line":1081,"column":42}},"203":{"start":{"line":1083,"column":8},"end":{"line":1085,"column":9}},"204":{"start":{"line":1084,"column":12},"end":{"line":1084,"column":34}},"205":{"start":{"line":1086,"column":8},"end":{"line":1086,"column":43}},"206":{"start":{"line":1091,"column":8},"end":{"line":1091,"column":32}},"207":{"start":{"line":1092,"column":8},"end":{"line":1092,"column":37}},"208":{"start":{"line":1108,"column":8},"end":{"line":1108,"column":20}},"209":{"start":{"line":1110,"column":8},"end":{"line":1120,"column":9}},"210":{"start":{"line":1111,"column":12},"end":{"line":1111,"column":24}},"211":{"start":{"line":1112,"column":12},"end":{"line":1119,"column":13}},"212":{"start":{"line":1113,"column":16},"end":{"line":1115,"column":17}},"213":{"start":{"line":1114,"column":20},"end":{"line":1114,"column":37}},"214":{"start":{"line":1116,"column":16},"end":{"line":1118,"column":17}},"215":{"start":{"line":1117,"column":20},"end":{"line":1117,"column":33}},"216":{"start":{"line":1122,"column":8},"end":{"line":1122,"column":20}},"217":{"start":{"line":1134,"column":8},"end":{"line":1146,"column":9}},"218":{"start":{"line":1136,"column":12},"end":{"line":1136,"column":34}},"219":{"start":{"line":1137,"column":12},"end":{"line":1137,"column":33}},"220":{"start":{"line":1139,"column":12},"end":{"line":1141,"column":13}},"221":{"start":{"line":1140,"column":16},"end":{"line":1140,"column":35}},"222":{"start":{"line":1143,"column":12},"end":{"line":1145,"column":13}},"223":{"start":{"line":1144,"column":16},"end":{"line":1144,"column":49}},"224":{"start":{"line":1156,"column":8},"end":{"line":1156,"column":53}},"225":{"start":{"line":1165,"column":8},"end":{"line":1165,"column":29}},"226":{"start":{"line":1179,"column":8},"end":{"line":1179,"column":27}},"227":{"start":{"line":1181,"column":8},"end":{"line":1183,"column":9}},"228":{"start":{"line":1182,"column":12},"end":{"line":1182,"column":71}},"229":{"start":{"line":1185,"column":8},"end":{"line":1191,"column":9}},"230":{"start":{"line":1186,"column":12},"end":{"line":1186,"column":43}},"231":{"start":{"line":1188,"column":12},"end":{"line":1190,"column":13}},"232":{"start":{"line":1189,"column":16},"end":{"line":1189,"column":34}},"233":{"start":{"line":1193,"column":8},"end":{"line":1199,"column":9}},"234":{"start":{"line":1194,"column":12},"end":{"line":1198,"column":13}},"235":{"start":{"line":1195,"column":16},"end":{"line":1195,"column":41}},"236":{"start":{"line":1197,"column":16},"end":{"line":1197,"column":46}},"237":{"start":{"line":1201,"column":8},"end":{"line":1206,"column":9}},"238":{"start":{"line":1202,"column":12},"end":{"line":1205,"column":15}},"239":{"start":{"line":1208,"column":8},"end":{"line":1210,"column":9}},"240":{"start":{"line":1209,"column":12},"end":{"line":1209,"column":29}},"241":{"start":{"line":1222,"column":0},"end":{"line":1268,"column":2}},"242":{"start":{"line":1230,"column":4},"end":{"line":1230,"column":17}},"243":{"start":{"line":1237,"column":4},"end":{"line":1237,"column":27}},"244":{"start":{"line":1244,"column":4},"end":{"line":1244,"column":23}},"245":{"start":{"line":1251,"column":4},"end":{"line":1251,"column":21}},"246":{"start":{"line":1253,"column":4},"end":{"line":1253,"column":22}},"247":{"start":{"line":1270,"column":0},"end":{"line":1358,"column":2}},"248":{"start":{"line":1274,"column":8},"end":{"line":1282,"column":9}},"249":{"start":{"line":1275,"column":12},"end":{"line":1281,"column":13}},"250":{"start":{"line":1276,"column":16},"end":{"line":1276,"column":31}},"251":{"start":{"line":1277,"column":16},"end":{"line":1277,"column":36}},"252":{"start":{"line":1279,"column":16},"end":{"line":1279,"column":38}},"253":{"start":{"line":1280,"column":16},"end":{"line":1280,"column":28}},"254":{"start":{"line":1283,"column":8},"end":{"line":1283,"column":31}},"255":{"start":{"line":1284,"column":8},"end":{"line":1299,"column":9}},"256":{"start":{"line":1286,"column":16},"end":{"line":1286,"column":56}},"257":{"start":{"line":1287,"column":16},"end":{"line":1287,"column":22}},"258":{"start":{"line":1289,"column":16},"end":{"line":1289,"column":58}},"259":{"start":{"line":1290,"column":16},"end":{"line":1290,"column":22}},"260":{"start":{"line":1292,"column":16},"end":{"line":1298,"column":17}},"261":{"start":{"line":1293,"column":20},"end":{"line":1293,"column":38}},"262":{"start":{"line":1294,"column":20},"end":{"line":1294,"column":52}},"263":{"start":{"line":1295,"column":20},"end":{"line":1295,"column":46}},"264":{"start":{"line":1297,"column":20},"end":{"line":1297,"column":42}},"265":{"start":{"line":1301,"column":8},"end":{"line":1303,"column":9}},"266":{"start":{"line":1302,"column":12},"end":{"line":1302,"column":29}},"267":{"start":{"line":1305,"column":8},"end":{"line":1305,"column":19}},"268":{"start":{"line":1315,"column":8},"end":{"line":1316,"column":23}},"269":{"start":{"line":1318,"column":8},"end":{"line":1320,"column":9}},"270":{"start":{"line":1319,"column":12},"end":{"line":1319,"column":61}},"271":{"start":{"line":1323,"column":8},"end":{"line":1331,"column":9}},"272":{"start":{"line":1324,"column":12},"end":{"line":1324,"column":44}},"273":{"start":{"line":1326,"column":12},"end":{"line":1330,"column":13}},"274":{"start":{"line":1327,"column":16},"end":{"line":1327,"column":48}},"275":{"start":{"line":1329,"column":16},"end":{"line":1329,"column":59}},"276":{"start":{"line":1333,"column":8},"end":{"line":1333,"column":19}},"277":{"start":{"line":1347,"column":8},"end":{"line":1351,"column":9}},"278":{"start":{"line":1348,"column":12},"end":{"line":1348,"column":66}},"279":{"start":{"line":1350,"column":12},"end":{"line":1350,"column":36}},"280":{"start":{"line":1355,"column":8},"end":{"line":1355,"column":23}},"281":{"start":{"line":1366,"column":0},"end":{"line":1383,"column":2}},"282":{"start":{"line":1374,"column":4},"end":{"line":1374,"column":19}},"283":{"start":{"line":1382,"column":4},"end":{"line":1382,"column":19}},"284":{"start":{"line":1385,"column":0},"end":{"line":1428,"column":2}},"285":{"start":{"line":1387,"column":8},"end":{"line":1387,"column":32}},"286":{"start":{"line":1388,"column":8},"end":{"line":1392,"column":9}},"287":{"start":{"line":1389,"column":12},"end":{"line":1391,"column":15}},"288":{"start":{"line":1390,"column":16},"end":{"line":1390,"column":40}},"289":{"start":{"line":1401,"column":8},"end":{"line":1401,"column":44}},"290":{"start":{"line":1402,"column":8},"end":{"line":1412,"column":9}},"291":{"start":{"line":1403,"column":12},"end":{"line":1410,"column":13}},"292":{"start":{"line":1404,"column":16},"end":{"line":1406,"column":17}},"293":{"start":{"line":1405,"column":20},"end":{"line":1405,"column":48}},"294":{"start":{"line":1408,"column":16},"end":{"line":1408,"column":38}},"295":{"start":{"line":1409,"column":16},"end":{"line":1409,"column":29}},"296":{"start":{"line":1414,"column":8},"end":{"line":1414,"column":24}},"297":{"start":{"line":1426,"column":8},"end":{"line":1426,"column":59}},"298":{"start":{"line":1454,"column":0},"end":{"line":1546,"column":6}},"299":{"start":{"line":1461,"column":8},"end":{"line":1461,"column":51}},"300":{"start":{"line":1473,"column":8},"end":{"line":1475,"column":9}},"301":{"start":{"line":1474,"column":12},"end":{"line":1474,"column":24}},"302":{"start":{"line":1477,"column":8},"end":{"line":1477,"column":45}},"303":{"start":{"line":1489,"column":8},"end":{"line":1489,"column":47}},"304":{"start":{"line":1491,"column":8},"end":{"line":1493,"column":9}},"305":{"start":{"line":1492,"column":12},"end":{"line":1492,"column":21}},"306":{"start":{"line":1495,"column":8},"end":{"line":1495,"column":36}},"307":{"start":{"line":1497,"column":8},"end":{"line":1500,"column":9}},"308":{"start":{"line":1498,"column":12},"end":{"line":1498,"column":25}},"309":{"start":{"line":1499,"column":12},"end":{"line":1499,"column":46}},"310":{"start":{"line":1502,"column":8},"end":{"line":1502,"column":42}},"311":{"start":{"line":1504,"column":8},"end":{"line":1510,"column":9}},"312":{"start":{"line":1505,"column":12},"end":{"line":1505,"column":46}},"313":{"start":{"line":1506,"column":12},"end":{"line":1506,"column":30}},"314":{"start":{"line":1507,"column":12},"end":{"line":1509,"column":13}},"315":{"start":{"line":1508,"column":16},"end":{"line":1508,"column":25}},"316":{"start":{"line":1513,"column":8},"end":{"line":1513,"column":72}},"317":{"start":{"line":1518,"column":8},"end":{"line":1519,"column":21}},"318":{"start":{"line":1521,"column":8},"end":{"line":1531,"column":9}},"319":{"start":{"line":1522,"column":12},"end":{"line":1530,"column":14}},"320":{"start":{"line":1533,"column":8},"end":{"line":1533,"column":34}},"321":{"start":{"line":1535,"column":8},"end":{"line":1545,"column":9}},"322":{"start":{"line":1536,"column":12},"end":{"line":1536,"column":45}},"323":{"start":{"line":1538,"column":12},"end":{"line":1540,"column":13}},"324":{"start":{"line":1539,"column":16},"end":{"line":1539,"column":43}},"325":{"start":{"line":1542,"column":12},"end":{"line":1544,"column":13}},"326":{"start":{"line":1543,"column":16},"end":{"line":1543,"column":46}},"327":{"start":{"line":1548,"column":0},"end":{"line":2313,"column":2}},"328":{"start":{"line":1565,"column":8},"end":{"line":1565,"column":52}},"329":{"start":{"line":1566,"column":8},"end":{"line":1570,"column":11}},"330":{"start":{"line":1567,"column":12},"end":{"line":1569,"column":13}},"331":{"start":{"line":1568,"column":16},"end":{"line":1568,"column":37}},"332":{"start":{"line":1571,"column":8},"end":{"line":1571,"column":22}},"333":{"start":{"line":1587,"column":8},"end":{"line":1587,"column":55}},"334":{"start":{"line":1588,"column":8},"end":{"line":1592,"column":11}},"335":{"start":{"line":1589,"column":12},"end":{"line":1591,"column":13}},"336":{"start":{"line":1590,"column":16},"end":{"line":1590,"column":37}},"337":{"start":{"line":1593,"column":8},"end":{"line":1593,"column":22}},"338":{"start":{"line":1613,"column":8},"end":{"line":1613,"column":67}},"339":{"start":{"line":1647,"column":8},"end":{"line":1650,"column":46}},"340":{"start":{"line":1653,"column":8},"end":{"line":1657,"column":11}},"341":{"start":{"line":1659,"column":8},"end":{"line":1695,"column":9}},"342":{"start":{"line":1661,"column":12},"end":{"line":1663,"column":13}},"343":{"start":{"line":1662,"column":16},"end":{"line":1662,"column":58}},"344":{"start":{"line":1665,"column":12},"end":{"line":1665,"column":19}},"345":{"start":{"line":1666,"column":12},"end":{"line":1666,"column":24}},"346":{"start":{"line":1667,"column":12},"end":{"line":1667,"column":50}},"347":{"start":{"line":1668,"column":12},"end":{"line":1668,"column":21}},"348":{"start":{"line":1670,"column":12},"end":{"line":1672,"column":13}},"349":{"start":{"line":1671,"column":16},"end":{"line":1671,"column":29}},"350":{"start":{"line":1674,"column":12},"end":{"line":1674,"column":32}},"351":{"start":{"line":1675,"column":12},"end":{"line":1675,"column":31}},"352":{"start":{"line":1677,"column":12},"end":{"line":1692,"column":21}},"353":{"start":{"line":1679,"column":16},"end":{"line":1682,"column":17}},"354":{"start":{"line":1680,"column":20},"end":{"line":1680,"column":60}},"355":{"start":{"line":1681,"column":20},"end":{"line":1681,"column":39}},"356":{"start":{"line":1684,"column":16},"end":{"line":1684,"column":53}},"357":{"start":{"line":1686,"column":16},"end":{"line":1686,"column":49}},"358":{"start":{"line":1687,"column":16},"end":{"line":1687,"column":28}},"359":{"start":{"line":1688,"column":16},"end":{"line":1688,"column":28}},"360":{"start":{"line":1690,"column":16},"end":{"line":1690,"column":52}},"361":{"start":{"line":1694,"column":12},"end":{"line":1694,"column":66}},"362":{"start":{"line":1697,"column":8},"end":{"line":1697,"column":34}},"363":{"start":{"line":1698,"column":8},"end":{"line":1698,"column":25}},"364":{"start":{"line":1699,"column":8},"end":{"line":1699,"column":29}},"365":{"start":{"line":1702,"column":8},"end":{"line":1706,"column":9}},"366":{"start":{"line":1703,"column":12},"end":{"line":1703,"column":50}},"367":{"start":{"line":1704,"column":12},"end":{"line":1704,"column":53}},"368":{"start":{"line":1705,"column":12},"end":{"line":1705,"column":39}},"369":{"start":{"line":1708,"column":8},"end":{"line":1708,"column":24}},"370":{"start":{"line":1710,"column":8},"end":{"line":1740,"column":9}},"371":{"start":{"line":1712,"column":12},"end":{"line":1712,"column":44}},"372":{"start":{"line":1713,"column":12},"end":{"line":1713,"column":51}},"373":{"start":{"line":1714,"column":12},"end":{"line":1714,"column":32}},"374":{"start":{"line":1716,"column":12},"end":{"line":1731,"column":13}},"375":{"start":{"line":1717,"column":16},"end":{"line":1717,"column":28}},"376":{"start":{"line":1719,"column":16},"end":{"line":1723,"column":17}},"377":{"start":{"line":1720,"column":20},"end":{"line":1720,"column":50}},"378":{"start":{"line":1721,"column":23},"end":{"line":1723,"column":17}},"379":{"start":{"line":1722,"column":20},"end":{"line":1722,"column":43}},"380":{"start":{"line":1725,"column":16},"end":{"line":1725,"column":58}},"381":{"start":{"line":1728,"column":16},"end":{"line":1730,"column":17}},"382":{"start":{"line":1729,"column":20},"end":{"line":1729,"column":32}},"383":{"start":{"line":1734,"column":12},"end":{"line":1738,"column":13}},"384":{"start":{"line":1735,"column":16},"end":{"line":1735,"column":49}},"385":{"start":{"line":1736,"column":19},"end":{"line":1738,"column":13}},"386":{"start":{"line":1737,"column":16},"end":{"line":1737,"column":47}},"387":{"start":{"line":1742,"column":8},"end":{"line":1750,"column":9}},"388":{"start":{"line":1743,"column":12},"end":{"line":1743,"column":59}},"389":{"start":{"line":1744,"column":12},"end":{"line":1744,"column":131}},"390":{"start":{"line":1747,"column":12},"end":{"line":1749,"column":13}},"391":{"start":{"line":1748,"column":16},"end":{"line":1748,"column":41}},"392":{"start":{"line":1752,"column":8},"end":{"line":1756,"column":9}},"393":{"start":{"line":1753,"column":12},"end":{"line":1753,"column":64}},"394":{"start":{"line":1754,"column":12},"end":{"line":1754,"column":76}},"395":{"start":{"line":1755,"column":12},"end":{"line":1755,"column":53}},"396":{"start":{"line":1758,"column":8},"end":{"line":1758,"column":46}},"397":{"start":{"line":1768,"column":8},"end":{"line":1768,"column":46}},"398":{"start":{"line":1789,"column":8},"end":{"line":1792,"column":56}},"399":{"start":{"line":1795,"column":8},"end":{"line":1806,"column":9}},"400":{"start":{"line":1796,"column":12},"end":{"line":1800,"column":13}},"401":{"start":{"line":1797,"column":16},"end":{"line":1799,"column":17}},"402":{"start":{"line":1798,"column":20},"end":{"line":1798,"column":48}},"403":{"start":{"line":1801,"column":12},"end":{"line":1803,"column":13}},"404":{"start":{"line":1802,"column":16},"end":{"line":1802,"column":60}},"405":{"start":{"line":1805,"column":12},"end":{"line":1805,"column":24}},"406":{"start":{"line":1808,"column":8},"end":{"line":1824,"column":10}},"407":{"start":{"line":1815,"column":12},"end":{"line":1815,"column":45}},"408":{"start":{"line":1816,"column":12},"end":{"line":1823,"column":13}},"409":{"start":{"line":1817,"column":16},"end":{"line":1822,"column":17}},"410":{"start":{"line":1818,"column":20},"end":{"line":1818,"column":40}},"411":{"start":{"line":1819,"column":20},"end":{"line":1821,"column":21}},"412":{"start":{"line":1820,"column":24},"end":{"line":1820,"column":44}},"413":{"start":{"line":1826,"column":8},"end":{"line":1856,"column":9}},"414":{"start":{"line":1828,"column":12},"end":{"line":1828,"column":40}},"415":{"start":{"line":1829,"column":12},"end":{"line":1829,"column":28}},"416":{"start":{"line":1830,"column":12},"end":{"line":1830,"column":67}},"417":{"start":{"line":1832,"column":12},"end":{"line":1844,"column":13}},"418":{"start":{"line":1833,"column":16},"end":{"line":1841,"column":17}},"419":{"start":{"line":1834,"column":20},"end":{"line":1834,"column":55}},"420":{"start":{"line":1836,"column":20},"end":{"line":1840,"column":21}},"421":{"start":{"line":1837,"column":24},"end":{"line":1839,"column":25}},"422":{"start":{"line":1838,"column":28},"end":{"line":1838,"column":60}},"423":{"start":{"line":1843,"column":16},"end":{"line":1843,"column":28}},"424":{"start":{"line":1847,"column":15},"end":{"line":1856,"column":9}},"425":{"start":{"line":1848,"column":12},"end":{"line":1848,"column":26}},"426":{"start":{"line":1849,"column":12},"end":{"line":1849,"column":24}},"427":{"start":{"line":1851,"column":15},"end":{"line":1856,"column":9}},"428":{"start":{"line":1852,"column":12},"end":{"line":1852,"column":50}},"429":{"start":{"line":1853,"column":12},"end":{"line":1853,"column":44}},"430":{"start":{"line":1854,"column":12},"end":{"line":1854,"column":36}},"431":{"start":{"line":1855,"column":12},"end":{"line":1855,"column":24}},"432":{"start":{"line":1858,"column":8},"end":{"line":1858,"column":45}},"433":{"start":{"line":1861,"column":8},"end":{"line":1873,"column":9}},"434":{"start":{"line":1862,"column":12},"end":{"line":1862,"column":50}},"435":{"start":{"line":1864,"column":12},"end":{"line":1872,"column":13}},"436":{"start":{"line":1865,"column":16},"end":{"line":1865,"column":44}},"437":{"start":{"line":1866,"column":16},"end":{"line":1866,"column":28}},"438":{"start":{"line":1868,"column":19},"end":{"line":1872,"column":13}},"439":{"start":{"line":1869,"column":16},"end":{"line":1869,"column":31}},"440":{"start":{"line":1870,"column":16},"end":{"line":1870,"column":52}},"441":{"start":{"line":1871,"column":16},"end":{"line":1871,"column":28}},"442":{"start":{"line":1876,"column":8},"end":{"line":1876,"column":28}},"443":{"start":{"line":1877,"column":8},"end":{"line":1879,"column":9}},"444":{"start":{"line":1878,"column":12},"end":{"line":1878,"column":35}},"445":{"start":{"line":1881,"column":8},"end":{"line":1881,"column":20}},"446":{"start":{"line":1890,"column":8},"end":{"line":1890,"column":50}},"447":{"start":{"line":1901,"column":8},"end":{"line":1901,"column":33}},"448":{"start":{"line":1913,"column":8},"end":{"line":1913,"column":53}},"449":{"start":{"line":1984,"column":8},"end":{"line":1987,"column":34}},"450":{"start":{"line":1989,"column":8},"end":{"line":2004,"column":9}},"451":{"start":{"line":1990,"column":12},"end":{"line":1992,"column":13}},"452":{"start":{"line":1991,"column":16},"end":{"line":1991,"column":43}},"453":{"start":{"line":1993,"column":12},"end":{"line":1993,"column":54}},"454":{"start":{"line":1995,"column":12},"end":{"line":1995,"column":21}},"455":{"start":{"line":1997,"column":12},"end":{"line":2002,"column":21}},"456":{"start":{"line":1998,"column":16},"end":{"line":2000,"column":17}},"457":{"start":{"line":1999,"column":20},"end":{"line":1999,"column":41}},"458":{"start":{"line":2001,"column":16},"end":{"line":2001,"column":63}},"459":{"start":{"line":2006,"column":8},"end":{"line":2006,"column":19}},"460":{"start":{"line":2024,"column":8},"end":{"line":2024,"column":45}},"461":{"start":{"line":2026,"column":8},"end":{"line":2030,"column":9}},"462":{"start":{"line":2027,"column":12},"end":{"line":2027,"column":49}},"463":{"start":{"line":2029,"column":12},"end":{"line":2029,"column":24}},"464":{"start":{"line":2048,"column":8},"end":{"line":2053,"column":36}},"465":{"start":{"line":2055,"column":8},"end":{"line":2055,"column":30}},"466":{"start":{"line":2058,"column":8},"end":{"line":2062,"column":9}},"467":{"start":{"line":2059,"column":12},"end":{"line":2061,"column":15}},"468":{"start":{"line":2064,"column":8},"end":{"line":2072,"column":9}},"469":{"start":{"line":2066,"column":12},"end":{"line":2066,"column":72}},"470":{"start":{"line":2068,"column":12},"end":{"line":2071,"column":13}},"471":{"start":{"line":2069,"column":16},"end":{"line":2069,"column":31}},"472":{"start":{"line":2070,"column":16},"end":{"line":2070,"column":37}},"473":{"start":{"line":2074,"column":8},"end":{"line":2076,"column":9}},"474":{"start":{"line":2075,"column":12},"end":{"line":2075,"column":41}},"475":{"start":{"line":2078,"column":8},"end":{"line":2078,"column":18}},"476":{"start":{"line":2099,"column":8},"end":{"line":2099,"column":33}},"477":{"start":{"line":2101,"column":8},"end":{"line":2115,"column":9}},"478":{"start":{"line":2102,"column":12},"end":{"line":2108,"column":13}},"479":{"start":{"line":2103,"column":16},"end":{"line":2103,"column":33}},"480":{"start":{"line":2104,"column":16},"end":{"line":2104,"column":52}},"481":{"start":{"line":2106,"column":16},"end":{"line":2106,"column":31}},"482":{"start":{"line":2107,"column":16},"end":{"line":2107,"column":38}},"483":{"start":{"line":2110,"column":12},"end":{"line":2114,"column":13}},"484":{"start":{"line":2111,"column":16},"end":{"line":2111,"column":47}},"485":{"start":{"line":2112,"column":16},"end":{"line":2112,"column":35}},"486":{"start":{"line":2113,"column":16},"end":{"line":2113,"column":52}},"487":{"start":{"line":2148,"column":8},"end":{"line":2157,"column":17}},"488":{"start":{"line":2159,"column":8},"end":{"line":2174,"column":9}},"489":{"start":{"line":2164,"column":12},"end":{"line":2170,"column":13}},"490":{"start":{"line":2165,"column":16},"end":{"line":2165,"column":38}},"491":{"start":{"line":2166,"column":19},"end":{"line":2170,"column":13}},"492":{"start":{"line":2167,"column":16},"end":{"line":2167,"column":52}},"493":{"start":{"line":2169,"column":16},"end":{"line":2169,"column":26}},"494":{"start":{"line":2173,"column":12},"end":{"line":2173,"column":73}},"495":{"start":{"line":2176,"column":8},"end":{"line":2178,"column":9}},"496":{"start":{"line":2177,"column":12},"end":{"line":2177,"column":36}},"497":{"start":{"line":2180,"column":8},"end":{"line":2182,"column":9}},"498":{"start":{"line":2181,"column":12},"end":{"line":2181,"column":33}},"499":{"start":{"line":2184,"column":8},"end":{"line":2184,"column":30}},"500":{"start":{"line":2186,"column":8},"end":{"line":2192,"column":9}},"501":{"start":{"line":2187,"column":12},"end":{"line":2187,"column":41}},"502":{"start":{"line":2189,"column":12},"end":{"line":2191,"column":13}},"503":{"start":{"line":2190,"column":16},"end":{"line":2190,"column":37}},"504":{"start":{"line":2195,"column":8},"end":{"line":2199,"column":9}},"505":{"start":{"line":2196,"column":12},"end":{"line":2198,"column":15}},"506":{"start":{"line":2202,"column":8},"end":{"line":2216,"column":9}},"507":{"start":{"line":2203,"column":12},"end":{"line":2205,"column":13}},"508":{"start":{"line":2204,"column":16},"end":{"line":2204,"column":60}},"509":{"start":{"line":2208,"column":12},"end":{"line":2208,"column":23}},"510":{"start":{"line":2211,"column":12},"end":{"line":2213,"column":13}},"511":{"start":{"line":2212,"column":16},"end":{"line":2212,"column":33}},"512":{"start":{"line":2215,"column":12},"end":{"line":2215,"column":33}},"513":{"start":{"line":2218,"column":8},"end":{"line":2218,"column":43}},"514":{"start":{"line":2222,"column":8},"end":{"line":2222,"column":16}},"515":{"start":{"line":2225,"column":8},"end":{"line":2233,"column":9}},"516":{"start":{"line":2226,"column":12},"end":{"line":2226,"column":35}},"517":{"start":{"line":2227,"column":12},"end":{"line":2227,"column":44}},"518":{"start":{"line":2228,"column":12},"end":{"line":2232,"column":13}},"519":{"start":{"line":2229,"column":16},"end":{"line":2229,"column":36}},"520":{"start":{"line":2230,"column":16},"end":{"line":2230,"column":36}},"521":{"start":{"line":2231,"column":16},"end":{"line":2231,"column":34}},"522":{"start":{"line":2235,"column":8},"end":{"line":2235,"column":19}},"523":{"start":{"line":2247,"column":8},"end":{"line":2247,"column":19}},"524":{"start":{"line":2249,"column":8},"end":{"line":2252,"column":9}},"525":{"start":{"line":2250,"column":12},"end":{"line":2250,"column":45}},"526":{"start":{"line":2251,"column":12},"end":{"line":2251,"column":54}},"527":{"start":{"line":2253,"column":8},"end":{"line":2253,"column":32}},"528":{"start":{"line":2254,"column":8},"end":{"line":2254,"column":31}},"529":{"start":{"line":2273,"column":8},"end":{"line":2273,"column":47}},"530":{"start":{"line":2275,"column":8},"end":{"line":2288,"column":9}},"531":{"start":{"line":2277,"column":16},"end":{"line":2277,"column":57}},"532":{"start":{"line":2284,"column":16},"end":{"line":2284,"column":35}},"533":{"start":{"line":2285,"column":16},"end":{"line":2285,"column":22}},"534":{"start":{"line":2287,"column":16},"end":{"line":2287,"column":43}},"535":{"start":{"line":2290,"column":8},"end":{"line":2290,"column":38}},"536":{"start":{"line":2310,"column":8},"end":{"line":2310,"column":46}},"537":{"start":{"line":2315,"column":0},"end":{"line":2315,"column":19}},"538":{"start":{"line":2318,"column":0},"end":{"line":2318,"column":23}},"539":{"start":{"line":2319,"column":0},"end":{"line":2319,"column":31}},"540":{"start":{"line":2321,"column":0},"end":{"line":2321,"column":56}},"541":{"start":{"line":2331,"column":0},"end":{"line":2331,"column":32}}},"branchMap":{"1":{"line":77,"type":"if","locations":[{"start":{"line":77,"column":8},"end":{"line":77,"column":8}},{"start":{"line":77,"column":8},"end":{"line":77,"column":8}}]},"2":{"line":114,"type":"if","locations":[{"start":{"line":114,"column":8},"end":{"line":114,"column":8}},{"start":{"line":114,"column":8},"end":{"line":114,"column":8}}]},"3":{"line":140,"type":"if","locations":[{"start":{"line":140,"column":8},"end":{"line":140,"column":8}},{"start":{"line":140,"column":8},"end":{"line":140,"column":8}}]},"4":{"line":147,"type":"if","locations":[{"start":{"line":147,"column":8},"end":{"line":147,"column":8}},{"start":{"line":147,"column":8},"end":{"line":147,"column":8}}]},"5":{"line":174,"type":"if","locations":[{"start":{"line":174,"column":8},"end":{"line":174,"column":8}},{"start":{"line":174,"column":8},"end":{"line":174,"column":8}}]},"6":{"line":228,"type":"if","locations":[{"start":{"line":228,"column":4},"end":{"line":228,"column":4}},{"start":{"line":228,"column":4},"end":{"line":228,"column":4}}]},"7":{"line":271,"type":"if","locations":[{"start":{"line":271,"column":8},"end":{"line":271,"column":8}},{"start":{"line":271,"column":8},"end":{"line":271,"column":8}}]},"8":{"line":273,"type":"if","locations":[{"start":{"line":273,"column":12},"end":{"line":273,"column":12}},{"start":{"line":273,"column":12},"end":{"line":273,"column":12}}]},"9":{"line":274,"type":"switch","locations":[{"start":{"line":275,"column":20},"end":{"line":276,"column":42}},{"start":{"line":277,"column":20},"end":{"line":279,"column":30}},{"start":{"line":280,"column":20},"end":{"line":282,"column":30}},{"start":{"line":283,"column":20},"end":{"line":283,"column":28}}]},"10":{"line":290,"type":"if","locations":[{"start":{"line":290,"column":4},"end":{"line":290,"column":4}},{"start":{"line":290,"column":4},"end":{"line":290,"column":4}}]},"11":{"line":299,"type":"if","locations":[{"start":{"line":299,"column":8},"end":{"line":299,"column":8}},{"start":{"line":299,"column":8},"end":{"line":299,"column":8}}]},"12":{"line":302,"type":"if","locations":[{"start":{"line":302,"column":12},"end":{"line":302,"column":12}},{"start":{"line":302,"column":12},"end":{"line":302,"column":12}}]},"13":{"line":302,"type":"binary-expr","locations":[{"start":{"line":302,"column":16},"end":{"line":302,"column":22}},{"start":{"line":302,"column":26},"end":{"line":302,"column":56}}]},"14":{"line":305,"type":"if","locations":[{"start":{"line":305,"column":19},"end":{"line":305,"column":19}},{"start":{"line":305,"column":19},"end":{"line":305,"column":19}}]},"15":{"line":305,"type":"binary-expr","locations":[{"start":{"line":305,"column":23},"end":{"line":305,"column":29}},{"start":{"line":305,"column":33},"end":{"line":305,"column":70}}]},"16":{"line":436,"type":"if","locations":[{"start":{"line":436,"column":12},"end":{"line":436,"column":12}},{"start":{"line":436,"column":12},"end":{"line":436,"column":12}}]},"17":{"line":436,"type":"binary-expr","locations":[{"start":{"line":436,"column":16},"end":{"line":436,"column":31}},{"start":{"line":436,"column":36},"end":{"line":436,"column":38}},{"start":{"line":436,"column":42},"end":{"line":436,"column":51}}]},"18":{"line":477,"type":"if","locations":[{"start":{"line":477,"column":4},"end":{"line":477,"column":4}},{"start":{"line":477,"column":4},"end":{"line":477,"column":4}}]},"19":{"line":495,"type":"if","locations":[{"start":{"line":495,"column":4},"end":{"line":495,"column":4}},{"start":{"line":495,"column":4},"end":{"line":495,"column":4}}]},"20":{"line":708,"type":"if","locations":[{"start":{"line":708,"column":8},"end":{"line":708,"column":8}},{"start":{"line":708,"column":8},"end":{"line":708,"column":8}}]},"21":{"line":712,"type":"if","locations":[{"start":{"line":712,"column":8},"end":{"line":712,"column":8}},{"start":{"line":712,"column":8},"end":{"line":712,"column":8}}]},"22":{"line":716,"type":"if","locations":[{"start":{"line":716,"column":8},"end":{"line":716,"column":8}},{"start":{"line":716,"column":8},"end":{"line":716,"column":8}}]},"23":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":12},"end":{"line":720,"column":12}},{"start":{"line":720,"column":12},"end":{"line":720,"column":12}}]},"24":{"line":724,"type":"if","locations":[{"start":{"line":724,"column":12},"end":{"line":724,"column":12}},{"start":{"line":724,"column":12},"end":{"line":724,"column":12}}]},"25":{"line":729,"type":"if","locations":[{"start":{"line":729,"column":8},"end":{"line":729,"column":8}},{"start":{"line":729,"column":8},"end":{"line":729,"column":8}}]},"26":{"line":730,"type":"cond-expr","locations":[{"start":{"line":730,"column":40},"end":{"line":730,"column":41}},{"start":{"line":730,"column":44},"end":{"line":730,"column":45}}]},"27":{"line":765,"type":"if","locations":[{"start":{"line":765,"column":8},"end":{"line":765,"column":8}},{"start":{"line":765,"column":8},"end":{"line":765,"column":8}}]},"28":{"line":770,"type":"if","locations":[{"start":{"line":770,"column":8},"end":{"line":770,"column":8}},{"start":{"line":770,"column":8},"end":{"line":770,"column":8}}]},"29":{"line":771,"type":"if","locations":[{"start":{"line":771,"column":12},"end":{"line":771,"column":12}},{"start":{"line":771,"column":12},"end":{"line":771,"column":12}}]},"30":{"line":777,"type":"if","locations":[{"start":{"line":777,"column":12},"end":{"line":777,"column":12}},{"start":{"line":777,"column":12},"end":{"line":777,"column":12}}]},"31":{"line":784,"type":"if","locations":[{"start":{"line":784,"column":8},"end":{"line":784,"column":8}},{"start":{"line":784,"column":8},"end":{"line":784,"column":8}}]},"32":{"line":785,"type":"if","locations":[{"start":{"line":785,"column":12},"end":{"line":785,"column":12}},{"start":{"line":785,"column":12},"end":{"line":785,"column":12}}]},"33":{"line":791,"type":"if","locations":[{"start":{"line":791,"column":12},"end":{"line":791,"column":12}},{"start":{"line":791,"column":12},"end":{"line":791,"column":12}}]},"34":{"line":831,"type":"if","locations":[{"start":{"line":831,"column":8},"end":{"line":831,"column":8}},{"start":{"line":831,"column":8},"end":{"line":831,"column":8}}]},"35":{"line":831,"type":"binary-expr","locations":[{"start":{"line":831,"column":12},"end":{"line":831,"column":25}},{"start":{"line":831,"column":29},"end":{"line":831,"column":39}}]},"36":{"line":838,"type":"if","locations":[{"start":{"line":838,"column":12},"end":{"line":838,"column":12}},{"start":{"line":838,"column":12},"end":{"line":838,"column":12}}]},"37":{"line":838,"type":"binary-expr","locations":[{"start":{"line":838,"column":16},"end":{"line":838,"column":31}},{"start":{"line":838,"column":35},"end":{"line":838,"column":56}}]},"38":{"line":842,"type":"if","locations":[{"start":{"line":842,"column":12},"end":{"line":842,"column":12}},{"start":{"line":842,"column":12},"end":{"line":842,"column":12}}]},"39":{"line":849,"type":"if","locations":[{"start":{"line":849,"column":8},"end":{"line":849,"column":8}},{"start":{"line":849,"column":8},"end":{"line":849,"column":8}}]},"40":{"line":850,"type":"if","locations":[{"start":{"line":850,"column":12},"end":{"line":850,"column":12}},{"start":{"line":850,"column":12},"end":{"line":850,"column":12}}]},"41":{"line":855,"type":"if","locations":[{"start":{"line":855,"column":12},"end":{"line":855,"column":12}},{"start":{"line":855,"column":12},"end":{"line":855,"column":12}}]},"42":{"line":861,"type":"if","locations":[{"start":{"line":861,"column":8},"end":{"line":861,"column":8}},{"start":{"line":861,"column":8},"end":{"line":861,"column":8}}]},"43":{"line":862,"type":"if","locations":[{"start":{"line":862,"column":12},"end":{"line":862,"column":12}},{"start":{"line":862,"column":12},"end":{"line":862,"column":12}}]},"44":{"line":880,"type":"cond-expr","locations":[{"start":{"line":880,"column":41},"end":{"line":880,"column":71}},{"start":{"line":880,"column":74},"end":{"line":880,"column":78}}]},"45":{"line":894,"type":"cond-expr","locations":[{"start":{"line":894,"column":41},"end":{"line":894,"column":71}},{"start":{"line":894,"column":74},"end":{"line":894,"column":78}}]},"46":{"line":896,"type":"if","locations":[{"start":{"line":896,"column":8},"end":{"line":896,"column":8}},{"start":{"line":896,"column":8},"end":{"line":896,"column":8}}]},"47":{"line":896,"type":"binary-expr","locations":[{"start":{"line":896,"column":12},"end":{"line":896,"column":26}},{"start":{"line":896,"column":30},"end":{"line":896,"column":39}}]},"48":{"line":916,"type":"cond-expr","locations":[{"start":{"line":916,"column":41},"end":{"line":916,"column":71}},{"start":{"line":916,"column":74},"end":{"line":916,"column":78}}]},"49":{"line":930,"type":"if","locations":[{"start":{"line":930,"column":8},"end":{"line":930,"column":8}},{"start":{"line":930,"column":8},"end":{"line":930,"column":8}}]},"50":{"line":930,"type":"binary-expr","locations":[{"start":{"line":930,"column":12},"end":{"line":930,"column":14}},{"start":{"line":930,"column":18},"end":{"line":930,"column":27}}]},"51":{"line":939,"type":"if","locations":[{"start":{"line":939,"column":8},"end":{"line":939,"column":8}},{"start":{"line":939,"column":8},"end":{"line":939,"column":8}}]},"52":{"line":942,"type":"if","locations":[{"start":{"line":942,"column":16},"end":{"line":942,"column":16}},{"start":{"line":942,"column":16},"end":{"line":942,"column":16}}]},"53":{"line":942,"type":"binary-expr","locations":[{"start":{"line":942,"column":20},"end":{"line":942,"column":21}},{"start":{"line":942,"column":26},"end":{"line":942,"column":29}},{"start":{"line":942,"column":33},"end":{"line":942,"column":44}}]},"54":{"line":949,"type":"if","locations":[{"start":{"line":949,"column":8},"end":{"line":949,"column":8}},{"start":{"line":949,"column":8},"end":{"line":949,"column":8}}]},"55":{"line":952,"type":"if","locations":[{"start":{"line":952,"column":16},"end":{"line":952,"column":16}},{"start":{"line":952,"column":16},"end":{"line":952,"column":16}}]},"56":{"line":952,"type":"binary-expr","locations":[{"start":{"line":952,"column":20},"end":{"line":952,"column":21}},{"start":{"line":952,"column":26},"end":{"line":952,"column":29}},{"start":{"line":952,"column":33},"end":{"line":952,"column":44}}]},"57":{"line":989,"type":"if","locations":[{"start":{"line":989,"column":8},"end":{"line":989,"column":8}},{"start":{"line":989,"column":8},"end":{"line":989,"column":8}}]},"58":{"line":989,"type":"binary-expr","locations":[{"start":{"line":989,"column":12},"end":{"line":989,"column":25}},{"start":{"line":989,"column":29},"end":{"line":989,"column":45}}]},"59":{"line":1046,"type":"if","locations":[{"start":{"line":1046,"column":8},"end":{"line":1046,"column":8}},{"start":{"line":1046,"column":8},"end":{"line":1046,"column":8}}]},"60":{"line":1046,"type":"binary-expr","locations":[{"start":{"line":1046,"column":12},"end":{"line":1046,"column":25}},{"start":{"line":1046,"column":29},"end":{"line":1046,"column":39}}]},"61":{"line":1055,"type":"if","locations":[{"start":{"line":1055,"column":12},"end":{"line":1055,"column":12}},{"start":{"line":1055,"column":12},"end":{"line":1055,"column":12}}]},"62":{"line":1059,"type":"if","locations":[{"start":{"line":1059,"column":12},"end":{"line":1059,"column":12}},{"start":{"line":1059,"column":12},"end":{"line":1059,"column":12}}]},"63":{"line":1078,"type":"if","locations":[{"start":{"line":1078,"column":8},"end":{"line":1078,"column":8}},{"start":{"line":1078,"column":8},"end":{"line":1078,"column":8}}]},"64":{"line":1083,"type":"if","locations":[{"start":{"line":1083,"column":8},"end":{"line":1083,"column":8}},{"start":{"line":1083,"column":8},"end":{"line":1083,"column":8}}]},"65":{"line":1086,"type":"cond-expr","locations":[{"start":{"line":1086,"column":30},"end":{"line":1086,"column":35}},{"start":{"line":1086,"column":38},"end":{"line":1086,"column":42}}]},"66":{"line":1091,"type":"binary-expr","locations":[{"start":{"line":1091,"column":18},"end":{"line":1091,"column":25}},{"start":{"line":1091,"column":29},"end":{"line":1091,"column":31}}]},"67":{"line":1112,"type":"if","locations":[{"start":{"line":1112,"column":12},"end":{"line":1112,"column":12}},{"start":{"line":1112,"column":12},"end":{"line":1112,"column":12}}]},"68":{"line":1112,"type":"binary-expr","locations":[{"start":{"line":1112,"column":16},"end":{"line":1112,"column":17}},{"start":{"line":1112,"column":21},"end":{"line":1112,"column":25}}]},"69":{"line":1113,"type":"if","locations":[{"start":{"line":1113,"column":16},"end":{"line":1113,"column":16}},{"start":{"line":1113,"column":16},"end":{"line":1113,"column":16}}]},"70":{"line":1116,"type":"if","locations":[{"start":{"line":1116,"column":16},"end":{"line":1116,"column":16}},{"start":{"line":1116,"column":16},"end":{"line":1116,"column":16}}]},"71":{"line":1134,"type":"if","locations":[{"start":{"line":1134,"column":8},"end":{"line":1134,"column":8}},{"start":{"line":1134,"column":8},"end":{"line":1134,"column":8}}]},"72":{"line":1134,"type":"binary-expr","locations":[{"start":{"line":1134,"column":12},"end":{"line":1134,"column":25}},{"start":{"line":1134,"column":29},"end":{"line":1134,"column":43}}]},"73":{"line":1139,"type":"if","locations":[{"start":{"line":1139,"column":12},"end":{"line":1139,"column":12}},{"start":{"line":1139,"column":12},"end":{"line":1139,"column":12}}]},"74":{"line":1143,"type":"if","locations":[{"start":{"line":1143,"column":12},"end":{"line":1143,"column":12}},{"start":{"line":1143,"column":12},"end":{"line":1143,"column":12}}]},"75":{"line":1181,"type":"if","locations":[{"start":{"line":1181,"column":8},"end":{"line":1181,"column":8}},{"start":{"line":1181,"column":8},"end":{"line":1181,"column":8}}]},"76":{"line":1182,"type":"cond-expr","locations":[{"start":{"line":1182,"column":38},"end":{"line":1182,"column":50}},{"start":{"line":1182,"column":53},"end":{"line":1182,"column":70}}]},"77":{"line":1185,"type":"if","locations":[{"start":{"line":1185,"column":8},"end":{"line":1185,"column":8}},{"start":{"line":1185,"column":8},"end":{"line":1185,"column":8}}]},"78":{"line":1188,"type":"if","locations":[{"start":{"line":1188,"column":12},"end":{"line":1188,"column":12}},{"start":{"line":1188,"column":12},"end":{"line":1188,"column":12}}]},"79":{"line":1188,"type":"binary-expr","locations":[{"start":{"line":1188,"column":16},"end":{"line":1188,"column":17}},{"start":{"line":1188,"column":21},"end":{"line":1188,"column":34}}]},"80":{"line":1193,"type":"if","locations":[{"start":{"line":1193,"column":8},"end":{"line":1193,"column":8}},{"start":{"line":1193,"column":8},"end":{"line":1193,"column":8}}]},"81":{"line":1194,"type":"if","locations":[{"start":{"line":1194,"column":12},"end":{"line":1194,"column":12}},{"start":{"line":1194,"column":12},"end":{"line":1194,"column":12}}]},"82":{"line":1201,"type":"if","locations":[{"start":{"line":1201,"column":8},"end":{"line":1201,"column":8}},{"start":{"line":1201,"column":8},"end":{"line":1201,"column":8}}]},"83":{"line":1201,"type":"binary-expr","locations":[{"start":{"line":1201,"column":12},"end":{"line":1201,"column":26}},{"start":{"line":1201,"column":30},"end":{"line":1201,"column":39}}]},"84":{"line":1208,"type":"if","locations":[{"start":{"line":1208,"column":8},"end":{"line":1208,"column":8}},{"start":{"line":1208,"column":8},"end":{"line":1208,"column":8}}]},"85":{"line":1274,"type":"if","locations":[{"start":{"line":1274,"column":8},"end":{"line":1274,"column":8}},{"start":{"line":1274,"column":8},"end":{"line":1274,"column":8}}]},"86":{"line":1274,"type":"binary-expr","locations":[{"start":{"line":1274,"column":12},"end":{"line":1274,"column":24}},{"start":{"line":1274,"column":28},"end":{"line":1274,"column":43}}]},"87":{"line":1275,"type":"if","locations":[{"start":{"line":1275,"column":12},"end":{"line":1275,"column":12}},{"start":{"line":1275,"column":12},"end":{"line":1275,"column":12}}]},"88":{"line":1284,"type":"switch","locations":[{"start":{"line":1285,"column":12},"end":{"line":1287,"column":22}},{"start":{"line":1288,"column":12},"end":{"line":1290,"column":22}},{"start":{"line":1291,"column":12},"end":{"line":1298,"column":17}}]},"89":{"line":1289,"type":"binary-expr","locations":[{"start":{"line":1289,"column":38},"end":{"line":1289,"column":45}},{"start":{"line":1289,"column":49},"end":{"line":1289,"column":53}}]},"90":{"line":1292,"type":"if","locations":[{"start":{"line":1292,"column":16},"end":{"line":1292,"column":16}},{"start":{"line":1292,"column":16},"end":{"line":1292,"column":16}}]},"91":{"line":1292,"type":"binary-expr","locations":[{"start":{"line":1292,"column":20},"end":{"line":1292,"column":21}},{"start":{"line":1292,"column":25},"end":{"line":1292,"column":29}}]},"92":{"line":1293,"type":"binary-expr","locations":[{"start":{"line":1293,"column":27},"end":{"line":1293,"column":31}},{"start":{"line":1293,"column":35},"end":{"line":1293,"column":37}}]},"93":{"line":1294,"type":"cond-expr","locations":[{"start":{"line":1294,"column":30},"end":{"line":1294,"column":44}},{"start":{"line":1294,"column":47},"end":{"line":1294,"column":51}}]},"94":{"line":1301,"type":"if","locations":[{"start":{"line":1301,"column":8},"end":{"line":1301,"column":8}},{"start":{"line":1301,"column":8},"end":{"line":1301,"column":8}}]},"95":{"line":1318,"type":"if","locations":[{"start":{"line":1318,"column":8},"end":{"line":1318,"column":8}},{"start":{"line":1318,"column":8},"end":{"line":1318,"column":8}}]},"96":{"line":1319,"type":"cond-expr","locations":[{"start":{"line":1319,"column":33},"end":{"line":1319,"column":47}},{"start":{"line":1319,"column":50},"end":{"line":1319,"column":60}}]},"97":{"line":1323,"type":"if","locations":[{"start":{"line":1323,"column":8},"end":{"line":1323,"column":8}},{"start":{"line":1323,"column":8},"end":{"line":1323,"column":8}}]},"98":{"line":1323,"type":"binary-expr","locations":[{"start":{"line":1323,"column":12},"end":{"line":1323,"column":20}},{"start":{"line":1323,"column":24},"end":{"line":1323,"column":42}}]},"99":{"line":1347,"type":"if","locations":[{"start":{"line":1347,"column":8},"end":{"line":1347,"column":8}},{"start":{"line":1347,"column":8},"end":{"line":1347,"column":8}}]},"100":{"line":1348,"type":"binary-expr","locations":[{"start":{"line":1348,"column":21},"end":{"line":1348,"column":35}},{"start":{"line":1348,"column":40},"end":{"line":1348,"column":64}}]},"101":{"line":1387,"type":"binary-expr","locations":[{"start":{"line":1387,"column":15},"end":{"line":1387,"column":16}},{"start":{"line":1387,"column":20},"end":{"line":1387,"column":24}}]},"102":{"line":1388,"type":"if","locations":[{"start":{"line":1388,"column":8},"end":{"line":1388,"column":8}},{"start":{"line":1388,"column":8},"end":{"line":1388,"column":8}}]},"103":{"line":1390,"type":"binary-expr","locations":[{"start":{"line":1390,"column":29},"end":{"line":1390,"column":30}},{"start":{"line":1390,"column":34},"end":{"line":1390,"column":35}}]},"104":{"line":1402,"type":"if","locations":[{"start":{"line":1402,"column":8},"end":{"line":1402,"column":8}},{"start":{"line":1402,"column":8},"end":{"line":1402,"column":8}}]},"105":{"line":1403,"type":"if","locations":[{"start":{"line":1403,"column":12},"end":{"line":1403,"column":12}},{"start":{"line":1403,"column":12},"end":{"line":1403,"column":12}}]},"106":{"line":1473,"type":"if","locations":[{"start":{"line":1473,"column":8},"end":{"line":1473,"column":8}},{"start":{"line":1473,"column":8},"end":{"line":1473,"column":8}}]},"107":{"line":1473,"type":"binary-expr","locations":[{"start":{"line":1473,"column":12},"end":{"line":1473,"column":16}},{"start":{"line":1473,"column":20},"end":{"line":1473,"column":25}},{"start":{"line":1473,"column":29},"end":{"line":1473,"column":64}}]},"108":{"line":1491,"type":"if","locations":[{"start":{"line":1491,"column":8},"end":{"line":1491,"column":8}},{"start":{"line":1491,"column":8},"end":{"line":1491,"column":8}}]},"109":{"line":1497,"type":"if","locations":[{"start":{"line":1497,"column":8},"end":{"line":1497,"column":8}},{"start":{"line":1497,"column":8},"end":{"line":1497,"column":8}}]},"110":{"line":1504,"type":"if","locations":[{"start":{"line":1504,"column":8},"end":{"line":1504,"column":8}},{"start":{"line":1504,"column":8},"end":{"line":1504,"column":8}}]},"111":{"line":1507,"type":"if","locations":[{"start":{"line":1507,"column":12},"end":{"line":1507,"column":12}},{"start":{"line":1507,"column":12},"end":{"line":1507,"column":12}}]},"112":{"line":1513,"type":"cond-expr","locations":[{"start":{"line":1513,"column":40},"end":{"line":1513,"column":56}},{"start":{"line":1513,"column":59},"end":{"line":1513,"column":60}}]},"113":{"line":1521,"type":"if","locations":[{"start":{"line":1521,"column":8},"end":{"line":1521,"column":8}},{"start":{"line":1521,"column":8},"end":{"line":1521,"column":8}}]},"114":{"line":1535,"type":"if","locations":[{"start":{"line":1535,"column":8},"end":{"line":1535,"column":8}},{"start":{"line":1535,"column":8},"end":{"line":1535,"column":8}}]},"115":{"line":1538,"type":"if","locations":[{"start":{"line":1538,"column":12},"end":{"line":1538,"column":12}},{"start":{"line":1538,"column":12},"end":{"line":1538,"column":12}}]},"116":{"line":1542,"type":"if","locations":[{"start":{"line":1542,"column":12},"end":{"line":1542,"column":12}},{"start":{"line":1542,"column":12},"end":{"line":1542,"column":12}}]},"117":{"line":1567,"type":"if","locations":[{"start":{"line":1567,"column":12},"end":{"line":1567,"column":12}},{"start":{"line":1567,"column":12},"end":{"line":1567,"column":12}}]},"118":{"line":1589,"type":"if","locations":[{"start":{"line":1589,"column":12},"end":{"line":1589,"column":12}},{"start":{"line":1589,"column":12},"end":{"line":1589,"column":12}}]},"119":{"line":1613,"type":"binary-expr","locations":[{"start":{"line":1613,"column":32},"end":{"line":1613,"column":35}},{"start":{"line":1613,"column":39},"end":{"line":1613,"column":65}}]},"120":{"line":1659,"type":"if","locations":[{"start":{"line":1659,"column":8},"end":{"line":1659,"column":8}},{"start":{"line":1659,"column":8},"end":{"line":1659,"column":8}}]},"121":{"line":1661,"type":"if","locations":[{"start":{"line":1661,"column":12},"end":{"line":1661,"column":12}},{"start":{"line":1661,"column":12},"end":{"line":1661,"column":12}}]},"122":{"line":1670,"type":"if","locations":[{"start":{"line":1670,"column":12},"end":{"line":1670,"column":12}},{"start":{"line":1670,"column":12},"end":{"line":1670,"column":12}}]},"123":{"line":1679,"type":"if","locations":[{"start":{"line":1679,"column":16},"end":{"line":1679,"column":16}},{"start":{"line":1679,"column":16},"end":{"line":1679,"column":16}}]},"124":{"line":1680,"type":"binary-expr","locations":[{"start":{"line":1680,"column":24},"end":{"line":1680,"column":28}},{"start":{"line":1680,"column":33},"end":{"line":1680,"column":58}}]},"125":{"line":1680,"type":"cond-expr","locations":[{"start":{"line":1680,"column":53},"end":{"line":1680,"column":54}},{"start":{"line":1680,"column":57},"end":{"line":1680,"column":58}}]},"126":{"line":1681,"type":"binary-expr","locations":[{"start":{"line":1681,"column":24},"end":{"line":1681,"column":33}},{"start":{"line":1681,"column":37},"end":{"line":1681,"column":38}}]},"127":{"line":1684,"type":"cond-expr","locations":[{"start":{"line":1684,"column":35},"end":{"line":1684,"column":47}},{"start":{"line":1684,"column":50},"end":{"line":1684,"column":52}}]},"128":{"line":1686,"type":"cond-expr","locations":[{"start":{"line":1686,"column":42},"end":{"line":1686,"column":43}},{"start":{"line":1686,"column":46},"end":{"line":1686,"column":47}}]},"129":{"line":1694,"type":"cond-expr","locations":[{"start":{"line":1694,"column":36},"end":{"line":1694,"column":40}},{"start":{"line":1694,"column":43},"end":{"line":1694,"column":65}}]},"130":{"line":1702,"type":"if","locations":[{"start":{"line":1702,"column":8},"end":{"line":1702,"column":8}},{"start":{"line":1702,"column":8},"end":{"line":1702,"column":8}}]},"131":{"line":1702,"type":"binary-expr","locations":[{"start":{"line":1702,"column":12},"end":{"line":1702,"column":16}},{"start":{"line":1702,"column":20},"end":{"line":1702,"column":44}},{"start":{"line":1702,"column":49},"end":{"line":1702,"column":77}}]},"132":{"line":1710,"type":"if","locations":[{"start":{"line":1710,"column":8},"end":{"line":1710,"column":8}},{"start":{"line":1710,"column":8},"end":{"line":1710,"column":8}}]},"133":{"line":1716,"type":"if","locations":[{"start":{"line":1716,"column":12},"end":{"line":1716,"column":12}},{"start":{"line":1716,"column":12},"end":{"line":1716,"column":12}}]},"134":{"line":1719,"type":"if","locations":[{"start":{"line":1719,"column":16},"end":{"line":1719,"column":16}},{"start":{"line":1719,"column":16},"end":{"line":1719,"column":16}}]},"135":{"line":1721,"type":"if","locations":[{"start":{"line":1721,"column":23},"end":{"line":1721,"column":23}},{"start":{"line":1721,"column":23},"end":{"line":1721,"column":23}}]},"136":{"line":1728,"type":"if","locations":[{"start":{"line":1728,"column":16},"end":{"line":1728,"column":16}},{"start":{"line":1728,"column":16},"end":{"line":1728,"column":16}}]},"137":{"line":1734,"type":"if","locations":[{"start":{"line":1734,"column":12},"end":{"line":1734,"column":12}},{"start":{"line":1734,"column":12},"end":{"line":1734,"column":12}}]},"138":{"line":1736,"type":"if","locations":[{"start":{"line":1736,"column":19},"end":{"line":1736,"column":19}},{"start":{"line":1736,"column":19},"end":{"line":1736,"column":19}}]},"139":{"line":1736,"type":"binary-expr","locations":[{"start":{"line":1736,"column":24},"end":{"line":1736,"column":29}},{"start":{"line":1736,"column":34},"end":{"line":1736,"column":42}}]},"140":{"line":1742,"type":"if","locations":[{"start":{"line":1742,"column":8},"end":{"line":1742,"column":8}},{"start":{"line":1742,"column":8},"end":{"line":1742,"column":8}}]},"141":{"line":1743,"type":"binary-expr","locations":[{"start":{"line":1743,"column":17},"end":{"line":1743,"column":36}},{"start":{"line":1743,"column":40},"end":{"line":1743,"column":58}}]},"142":{"line":1744,"type":"cond-expr","locations":[{"start":{"line":1744,"column":66},"end":{"line":1744,"column":96}},{"start":{"line":1744,"column":99},"end":{"line":1744,"column":103}}]},"143":{"line":1744,"type":"cond-expr","locations":[{"start":{"line":1744,"column":115},"end":{"line":1744,"column":122}},{"start":{"line":1744,"column":125},"end":{"line":1744,"column":129}}]},"144":{"line":1747,"type":"if","locations":[{"start":{"line":1747,"column":12},"end":{"line":1747,"column":12}},{"start":{"line":1747,"column":12},"end":{"line":1747,"column":12}}]},"145":{"line":1752,"type":"if","locations":[{"start":{"line":1752,"column":8},"end":{"line":1752,"column":8}},{"start":{"line":1752,"column":8},"end":{"line":1752,"column":8}}]},"146":{"line":1753,"type":"binary-expr","locations":[{"start":{"line":1753,"column":36},"end":{"line":1753,"column":57}},{"start":{"line":1753,"column":61},"end":{"line":1753,"column":63}}]},"147":{"line":1754,"type":"binary-expr","locations":[{"start":{"line":1754,"column":42},"end":{"line":1754,"column":69}},{"start":{"line":1754,"column":73},"end":{"line":1754,"column":75}}]},"148":{"line":1758,"type":"cond-expr","locations":[{"start":{"line":1758,"column":32},"end":{"line":1758,"column":36}},{"start":{"line":1758,"column":39},"end":{"line":1758,"column":45}}]},"149":{"line":1792,"type":"binary-expr","locations":[{"start":{"line":1792,"column":21},"end":{"line":1792,"column":25}},{"start":{"line":1792,"column":30},"end":{"line":1792,"column":54}}]},"150":{"line":1795,"type":"if","locations":[{"start":{"line":1795,"column":8},"end":{"line":1795,"column":8}},{"start":{"line":1795,"column":8},"end":{"line":1795,"column":8}}]},"151":{"line":1795,"type":"binary-expr","locations":[{"start":{"line":1795,"column":12},"end":{"line":1795,"column":17}},{"start":{"line":1795,"column":22},"end":{"line":1795,"column":32}}]},"152":{"line":1797,"type":"if","locations":[{"start":{"line":1797,"column":16},"end":{"line":1797,"column":16}},{"start":{"line":1797,"column":16},"end":{"line":1797,"column":16}}]},"153":{"line":1801,"type":"if","locations":[{"start":{"line":1801,"column":12},"end":{"line":1801,"column":12}},{"start":{"line":1801,"column":12},"end":{"line":1801,"column":12}}]},"154":{"line":1809,"type":"cond-expr","locations":[{"start":{"line":1809,"column":44},"end":{"line":1809,"column":52}},{"start":{"line":1809,"column":55},"end":{"line":1809,"column":59}}]},"155":{"line":1810,"type":"cond-expr","locations":[{"start":{"line":1810,"column":30},"end":{"line":1810,"column":38}},{"start":{"line":1810,"column":41},"end":{"line":1810,"column":45}}]},"156":{"line":1816,"type":"if","locations":[{"start":{"line":1816,"column":12},"end":{"line":1816,"column":12}},{"start":{"line":1816,"column":12},"end":{"line":1816,"column":12}}]},"157":{"line":1819,"type":"if","locations":[{"start":{"line":1819,"column":20},"end":{"line":1819,"column":20}},{"start":{"line":1819,"column":20},"end":{"line":1819,"column":20}}]},"158":{"line":1819,"type":"binary-expr","locations":[{"start":{"line":1819,"column":24},"end":{"line":1819,"column":40}},{"start":{"line":1819,"column":44},"end":{"line":1819,"column":58}}]},"159":{"line":1826,"type":"if","locations":[{"start":{"line":1826,"column":8},"end":{"line":1826,"column":8}},{"start":{"line":1826,"column":8},"end":{"line":1826,"column":8}}]},"160":{"line":1830,"type":"cond-expr","locations":[{"start":{"line":1830,"column":36},"end":{"line":1830,"column":59}},{"start":{"line":1830,"column":62},"end":{"line":1830,"column":66}}]},"161":{"line":1832,"type":"if","locations":[{"start":{"line":1832,"column":12},"end":{"line":1832,"column":12}},{"start":{"line":1832,"column":12},"end":{"line":1832,"column":12}}]},"162":{"line":1833,"type":"if","locations":[{"start":{"line":1833,"column":16},"end":{"line":1833,"column":16}},{"start":{"line":1833,"column":16},"end":{"line":1833,"column":16}}]},"163":{"line":1837,"type":"if","locations":[{"start":{"line":1837,"column":24},"end":{"line":1837,"column":24}},{"start":{"line":1837,"column":24},"end":{"line":1837,"column":24}}]},"164":{"line":1847,"type":"if","locations":[{"start":{"line":1847,"column":15},"end":{"line":1847,"column":15}},{"start":{"line":1847,"column":15},"end":{"line":1847,"column":15}}]},"165":{"line":1847,"type":"binary-expr","locations":[{"start":{"line":1847,"column":19},"end":{"line":1847,"column":35}},{"start":{"line":1847,"column":39},"end":{"line":1847,"column":50}}]},"166":{"line":1851,"type":"if","locations":[{"start":{"line":1851,"column":15},"end":{"line":1851,"column":15}},{"start":{"line":1851,"column":15},"end":{"line":1851,"column":15}}]},"167":{"line":1851,"type":"binary-expr","locations":[{"start":{"line":1851,"column":19},"end":{"line":1851,"column":25}},{"start":{"line":1851,"column":31},"end":{"line":1851,"column":41}},{"start":{"line":1851,"column":47},"end":{"line":1851,"column":75}}]},"168":{"line":1861,"type":"if","locations":[{"start":{"line":1861,"column":8},"end":{"line":1861,"column":8}},{"start":{"line":1861,"column":8},"end":{"line":1861,"column":8}}]},"169":{"line":1864,"type":"if","locations":[{"start":{"line":1864,"column":12},"end":{"line":1864,"column":12}},{"start":{"line":1864,"column":12},"end":{"line":1864,"column":12}}]},"170":{"line":1864,"type":"binary-expr","locations":[{"start":{"line":1864,"column":16},"end":{"line":1864,"column":21}},{"start":{"line":1864,"column":25},"end":{"line":1864,"column":37}}]},"171":{"line":1868,"type":"if","locations":[{"start":{"line":1868,"column":19},"end":{"line":1868,"column":19}},{"start":{"line":1868,"column":19},"end":{"line":1868,"column":19}}]},"172":{"line":1868,"type":"binary-expr","locations":[{"start":{"line":1868,"column":23},"end":{"line":1868,"column":28}},{"start":{"line":1868,"column":33},"end":{"line":1868,"column":39}},{"start":{"line":1868,"column":43},"end":{"line":1868,"column":47}},{"start":{"line":1868,"column":52},"end":{"line":1868,"column":75}}]},"173":{"line":1877,"type":"if","locations":[{"start":{"line":1877,"column":8},"end":{"line":1877,"column":8}},{"start":{"line":1877,"column":8},"end":{"line":1877,"column":8}}]},"174":{"line":1989,"type":"if","locations":[{"start":{"line":1989,"column":8},"end":{"line":1989,"column":8}},{"start":{"line":1989,"column":8},"end":{"line":1989,"column":8}}]},"175":{"line":1990,"type":"if","locations":[{"start":{"line":1990,"column":12},"end":{"line":1990,"column":12}},{"start":{"line":1990,"column":12},"end":{"line":1990,"column":12}}]},"176":{"line":1998,"type":"if","locations":[{"start":{"line":1998,"column":16},"end":{"line":1998,"column":16}},{"start":{"line":1998,"column":16},"end":{"line":1998,"column":16}}]},"177":{"line":2001,"type":"binary-expr","locations":[{"start":{"line":2001,"column":52},"end":{"line":2001,"column":53}},{"start":{"line":2001,"column":57},"end":{"line":2001,"column":61}}]},"178":{"line":2026,"type":"if","locations":[{"start":{"line":2026,"column":8},"end":{"line":2026,"column":8}},{"start":{"line":2026,"column":8},"end":{"line":2026,"column":8}}]},"179":{"line":2058,"type":"if","locations":[{"start":{"line":2058,"column":8},"end":{"line":2058,"column":8}},{"start":{"line":2058,"column":8},"end":{"line":2058,"column":8}}]},"180":{"line":2058,"type":"binary-expr","locations":[{"start":{"line":2058,"column":13},"end":{"line":2058,"column":31}},{"start":{"line":2058,"column":35},"end":{"line":2058,"column":38}},{"start":{"line":2058,"column":44},"end":{"line":2058,"column":46}},{"start":{"line":2058,"column":50},"end":{"line":2058,"column":62}}]},"181":{"line":2064,"type":"if","locations":[{"start":{"line":2064,"column":8},"end":{"line":2064,"column":8}},{"start":{"line":2064,"column":8},"end":{"line":2064,"column":8}}]},"182":{"line":2068,"type":"if","locations":[{"start":{"line":2068,"column":12},"end":{"line":2068,"column":12}},{"start":{"line":2068,"column":12},"end":{"line":2068,"column":12}}]},"183":{"line":2074,"type":"if","locations":[{"start":{"line":2074,"column":8},"end":{"line":2074,"column":8}},{"start":{"line":2074,"column":8},"end":{"line":2074,"column":8}}]},"184":{"line":2101,"type":"if","locations":[{"start":{"line":2101,"column":8},"end":{"line":2101,"column":8}},{"start":{"line":2101,"column":8},"end":{"line":2101,"column":8}}]},"185":{"line":2102,"type":"if","locations":[{"start":{"line":2102,"column":12},"end":{"line":2102,"column":12}},{"start":{"line":2102,"column":12},"end":{"line":2102,"column":12}}]},"186":{"line":2110,"type":"if","locations":[{"start":{"line":2110,"column":12},"end":{"line":2110,"column":12}},{"start":{"line":2110,"column":12},"end":{"line":2110,"column":12}}]},"187":{"line":2110,"type":"binary-expr","locations":[{"start":{"line":2110,"column":17},"end":{"line":2110,"column":46}},{"start":{"line":2110,"column":51},"end":{"line":2110,"column":54}},{"start":{"line":2110,"column":58},"end":{"line":2110,"column":70}},{"start":{"line":2110,"column":77},"end":{"line":2110,"column":79}},{"start":{"line":2110,"column":83},"end":{"line":2110,"column":95}}]},"188":{"line":2159,"type":"if","locations":[{"start":{"line":2159,"column":8},"end":{"line":2159,"column":8}},{"start":{"line":2159,"column":8},"end":{"line":2159,"column":8}}]},"189":{"line":2159,"type":"binary-expr","locations":[{"start":{"line":2159,"column":12},"end":{"line":2159,"column":24}},{"start":{"line":2159,"column":28},"end":{"line":2159,"column":41}}]},"190":{"line":2164,"type":"if","locations":[{"start":{"line":2164,"column":12},"end":{"line":2164,"column":12}},{"start":{"line":2164,"column":12},"end":{"line":2164,"column":12}}]},"191":{"line":2166,"type":"if","locations":[{"start":{"line":2166,"column":19},"end":{"line":2166,"column":19}},{"start":{"line":2166,"column":19},"end":{"line":2166,"column":19}}]},"192":{"line":2173,"type":"cond-expr","locations":[{"start":{"line":2173,"column":65},"end":{"line":2173,"column":66}},{"start":{"line":2173,"column":69},"end":{"line":2173,"column":70}}]},"193":{"line":2176,"type":"if","locations":[{"start":{"line":2176,"column":8},"end":{"line":2176,"column":8}},{"start":{"line":2176,"column":8},"end":{"line":2176,"column":8}}]},"194":{"line":2177,"type":"binary-expr","locations":[{"start":{"line":2177,"column":17},"end":{"line":2177,"column":21}},{"start":{"line":2177,"column":25},"end":{"line":2177,"column":34}}]},"195":{"line":2180,"type":"if","locations":[{"start":{"line":2180,"column":8},"end":{"line":2180,"column":8}},{"start":{"line":2180,"column":8},"end":{"line":2180,"column":8}}]},"196":{"line":2186,"type":"if","locations":[{"start":{"line":2186,"column":8},"end":{"line":2186,"column":8}},{"start":{"line":2186,"column":8},"end":{"line":2186,"column":8}}]},"197":{"line":2189,"type":"if","locations":[{"start":{"line":2189,"column":12},"end":{"line":2189,"column":12}},{"start":{"line":2189,"column":12},"end":{"line":2189,"column":12}}]},"198":{"line":2189,"type":"binary-expr","locations":[{"start":{"line":2189,"column":16},"end":{"line":2189,"column":19}},{"start":{"line":2189,"column":23},"end":{"line":2189,"column":26}}]},"199":{"line":2195,"type":"if","locations":[{"start":{"line":2195,"column":8},"end":{"line":2195,"column":8}},{"start":{"line":2195,"column":8},"end":{"line":2195,"column":8}}]},"200":{"line":2195,"type":"binary-expr","locations":[{"start":{"line":2195,"column":13},"end":{"line":2195,"column":31}},{"start":{"line":2195,"column":36},"end":{"line":2195,"column":39}},{"start":{"line":2195,"column":43},"end":{"line":2195,"column":55}},{"start":{"line":2195,"column":62},"end":{"line":2195,"column":64}},{"start":{"line":2195,"column":68},"end":{"line":2195,"column":80}}]},"201":{"line":2196,"type":"binary-expr","locations":[{"start":{"line":2196,"column":35},"end":{"line":2196,"column":37}},{"start":{"line":2196,"column":41},"end":{"line":2196,"column":42}}]},"202":{"line":2202,"type":"if","locations":[{"start":{"line":2202,"column":8},"end":{"line":2202,"column":8}},{"start":{"line":2202,"column":8},"end":{"line":2202,"column":8}}]},"203":{"line":2203,"type":"if","locations":[{"start":{"line":2203,"column":12},"end":{"line":2203,"column":12}},{"start":{"line":2203,"column":12},"end":{"line":2203,"column":12}}]},"204":{"line":2211,"type":"if","locations":[{"start":{"line":2211,"column":12},"end":{"line":2211,"column":12}},{"start":{"line":2211,"column":12},"end":{"line":2211,"column":12}}]},"205":{"line":2218,"type":"cond-expr","locations":[{"start":{"line":2218,"column":32},"end":{"line":2218,"column":36}},{"start":{"line":2218,"column":39},"end":{"line":2218,"column":42}}]},"206":{"line":2225,"type":"if","locations":[{"start":{"line":2225,"column":8},"end":{"line":2225,"column":8}},{"start":{"line":2225,"column":8},"end":{"line":2225,"column":8}}]},"207":{"line":2228,"type":"if","locations":[{"start":{"line":2228,"column":12},"end":{"line":2228,"column":12}},{"start":{"line":2228,"column":12},"end":{"line":2228,"column":12}}]},"208":{"line":2249,"type":"if","locations":[{"start":{"line":2249,"column":8},"end":{"line":2249,"column":8}},{"start":{"line":2249,"column":8},"end":{"line":2249,"column":8}}]},"209":{"line":2251,"type":"cond-expr","locations":[{"start":{"line":2251,"column":27},"end":{"line":2251,"column":46}},{"start":{"line":2251,"column":49},"end":{"line":2251,"column":53}}]},"210":{"line":2254,"type":"binary-expr","locations":[{"start":{"line":2254,"column":15},"end":{"line":2254,"column":22}},{"start":{"line":2254,"column":26},"end":{"line":2254,"column":30}}]},"211":{"line":2275,"type":"switch","locations":[{"start":{"line":2276,"column":12},"end":{"line":2277,"column":57}},{"start":{"line":2278,"column":12},"end":{"line":2278,"column":25}},{"start":{"line":2283,"column":12},"end":{"line":2285,"column":22}},{"start":{"line":2286,"column":12},"end":{"line":2287,"column":43}}]},"212":{"line":2321,"type":"binary-expr","locations":[{"start":{"line":2321,"column":23},"end":{"line":2321,"column":43}},{"start":{"line":2321,"column":47},"end":{"line":2321,"column":55}}]}},"code":["(function () { YUI.add('event-custom-base', function (Y, NAME) {","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," */","","Y.Env.evt = {"," handles: {},"," plugins: {}","};","","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * Allows for the insertion of methods that are executed before or after"," * a specified method"," * @class Do"," * @static"," */","","var DO_BEFORE = 0,"," DO_AFTER = 1,","","DO = {",""," /**"," * Cache of objects touched by the utility"," * @property objs"," * @static"," * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object"," * replaces the role of this property, but is considered to be private, and"," * is only mentioned to provide a migration path."," *"," * If you have a use case which warrants migration to the _yuiaop property,"," * please file a ticket to let us know what it's used for and we can see if"," * we need to expose hooks for that functionality more formally."," */"," objs: null,",""," /**"," * <p>Execute the supplied method before the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>"," * <dd>Replace the arguments that the original function will be"," * called with.</dd>"," * <dt></code>Y.Do.Prevent(message)</code></dt>"," * <dd>Don't execute the wrapped function. Other before phase"," * wrappers will be executed.</dd>"," * </dl>"," *"," * @method before"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {string} handle for the subscription"," * @static"," */"," before: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_BEFORE, f, obj, sFn);"," },",""," /**"," * <p>Execute the supplied method after the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>"," * <dd>Return <code>returnValue</code> instead of the wrapped"," * method's original return value. This can be further altered by"," * other after phase wrappers.</dd>"," * </dl>"," *"," * <p>The static properties <code>Y.Do.originalRetVal</code> and"," * <code>Y.Do.currentRetVal</code> will be populated for reference.</p>"," *"," * @method after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * @return {string} handle for the subscription"," * @static"," */"," after: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_AFTER, f, obj, sFn);"," },",""," /**"," * Execute the supplied method before or after the specified function."," * Used by <code>before</code> and <code>after</code>."," *"," * @method _inject"," * @param when {string} before or after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @return {string} handle for the subscription"," * @private"," * @static"," */"," _inject: function(when, fn, obj, sFn) {"," // object id"," var id = Y.stamp(obj), o, sid;",""," if (!obj._yuiaop) {"," // create a map entry for the obj if it doesn't exist, to hold overridden methods"," obj._yuiaop = {};"," }",""," o = obj._yuiaop;",""," if (!o[sFn]) {"," // create a map entry for the method if it doesn't exist"," o[sFn] = new Y.Do.Method(obj, sFn);",""," // re-route the method to our wrapper"," obj[sFn] = function() {"," return o[sFn].exec.apply(o[sFn], arguments);"," };"," }",""," // subscriber id"," sid = id + Y.stamp(fn) + sFn;",""," // register the callback"," o[sFn].register(sid, fn, when);",""," return new Y.EventHandle(o[sFn], sid);"," },",""," /**"," * Detach a before or after subscription."," *"," * @method detach"," * @param handle {string} the subscription handle"," * @static"," */"," detach: function(handle) {"," if (handle.detach) {"," handle.detach();"," }"," }","};","","Y.Do = DO;","","//////////////////////////////////////////////////////////////////////////","","/**"," * Contains the return value from the wrapped method, accessible"," * by 'after' event listeners."," *"," * @property originalRetVal"," * @static"," * @since 3.2.0"," */","","/**"," * Contains the current state of the return value, consumable by"," * 'after' event listeners, and updated if an after subscriber"," * changes the return value generated by the wrapped function."," *"," * @property currentRetVal"," * @static"," * @since 3.2.0"," */","","//////////////////////////////////////////////////////////////////////////","","/**"," * Wrapper for a displaced method with aop enabled"," * @class Do.Method"," * @constructor"," * @param obj The object to operate on"," * @param sFn The name of the method to displace"," */","DO.Method = function(obj, sFn) {"," this.obj = obj;"," this.methodName = sFn;"," this.method = obj[sFn];"," this.before = {};"," this.after = {};","};","","/**"," * Register a aop subscriber"," * @method register"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype.register = function (sid, fn, when) {"," if (when) {"," this.after[sid] = fn;"," } else {"," this.before[sid] = fn;"," }","};","","/**"," * Unregister a aop subscriber"," * @method delete"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype._delete = function (sid) {"," delete this.before[sid];"," delete this.after[sid];","};","","/**"," * <p>Execute the wrapped method. All arguments are passed into the wrapping"," * functions. If any of the before wrappers return an instance of"," * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped"," * function nor any after phase subscribers will be executed.</p>"," *"," * <p>The return value will be the return value of the wrapped function or one"," * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or"," * <code>Y.Do.AlterReturn</code>."," *"," * @method exec"," * @param arg* {any} Arguments are passed to the wrapping and wrapped functions"," * @return {any} Return value of wrapped function unless overwritten (see above)"," */","DO.Method.prototype.exec = function () {",""," var args = Y.Array(arguments, 0, true),"," i, ret, newRet,"," bf = this.before,"," af = this.after,"," prevented = false;",""," // execute before"," for (i in bf) {"," if (bf.hasOwnProperty(i)) {"," ret = bf[i].apply(this.obj, args);"," if (ret) {"," switch (ret.constructor) {"," case DO.Halt:"," return ret.retVal;"," case DO.AlterArgs:"," args = ret.newArgs;"," break;"," case DO.Prevent:"," prevented = true;"," break;"," default:"," }"," }"," }"," }",""," // execute method"," if (!prevented) {"," ret = this.method.apply(this.obj, args);"," }",""," DO.originalRetVal = ret;"," DO.currentRetVal = ret;",""," // execute after methods."," for (i in af) {"," if (af.hasOwnProperty(i)) {"," newRet = af[i].apply(this.obj, args);"," // Stop processing if a Halt object is returned"," if (newRet && newRet.constructor === DO.Halt) {"," return newRet.retVal;"," // Check for a new return value"," } else if (newRet && newRet.constructor === DO.AlterReturn) {"," ret = newRet.newRetVal;"," // Update the static retval state"," DO.currentRetVal = ret;"," }"," }"," }",""," return ret;","};","","//////////////////////////////////////////////////////////////////////////","","/**"," * Return an AlterArgs object when you want to change the arguments that"," * were passed into the function. Useful for Do.before subscribers. An"," * example would be a service that scrubs out illegal characters prior to"," * executing the core business logic."," * @class Do.AlterArgs"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param newArgs {Array} Call parameters to be used for the original method"," * instead of the arguments originally passed in."," */","DO.AlterArgs = function(msg, newArgs) {"," this.msg = msg;"," this.newArgs = newArgs;","};","","/**"," * Return an AlterReturn object when you want to change the result returned"," * from the core method to the caller. Useful for Do.after subscribers."," * @class Do.AlterReturn"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param newRetVal {any} Return value passed to code that invoked the wrapped"," * function."," */","DO.AlterReturn = function(msg, newRetVal) {"," this.msg = msg;"," this.newRetVal = newRetVal;","};","","/**"," * Return a Halt object when you want to terminate the execution"," * of all subsequent subscribers as well as the wrapped method"," * if it has not exectued yet. Useful for Do.before subscribers."," * @class Do.Halt"," * @constructor"," * @param msg {String} (optional) Explanation of why the termination was done"," * @param retVal {any} Return value passed to code that invoked the wrapped"," * function."," */","DO.Halt = function(msg, retVal) {"," this.msg = msg;"," this.retVal = retVal;","};","","/**"," * Return a Prevent object when you want to prevent the wrapped function"," * from executing, but want the remaining listeners to execute. Useful"," * for Do.before subscribers."," * @class Do.Prevent"," * @constructor"," * @param msg {String} (optional) Explanation of why the termination was done"," */","DO.Prevent = function(msg) {"," this.msg = msg;","};","","/**"," * Return an Error object when you want to terminate the execution"," * of all subsequent method calls."," * @class Do.Error"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param retVal {any} Return value passed to code that invoked the wrapped"," * function."," * @deprecated use Y.Do.Halt or Y.Do.Prevent"," */","DO.Error = DO.Halt;","","","//////////////////////////////////////////////////////////////////////////","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","","// var onsubscribeType = \"_event:onsub\",","var YArray = Y.Array,",""," AFTER = 'after',"," CONFIGS = ["," 'broadcast',"," 'monitored',"," 'bubbles',"," 'context',"," 'contextFn',"," 'currentTarget',"," 'defaultFn',"," 'defaultTargetOnly',"," 'details',"," 'emitFacade',"," 'fireOnce',"," 'async',"," 'host',"," 'preventable',"," 'preventedFn',"," 'queuable',"," 'silent',"," 'stoppedFn',"," 'target',"," 'type'"," ],",""," CONFIGS_HASH = YArray.hash(CONFIGS),",""," nativeSlice = Array.prototype.slice,",""," YUI3_SIGNATURE = 9,"," YUI_LOG = 'yui:log',",""," mixConfigs = function(r, s, ov) {"," var p;",""," for (p in s) {"," if (CONFIGS_HASH[p] && (ov || !(p in r))) {"," r[p] = s[p];"," }"," }",""," return r;"," };","","/**"," * The CustomEvent class lets you define events for your application"," * that can be subscribed to by one or more independent component."," *"," * @param {String} type The type of event, which is passed to the callback"," * when the event fires."," * @param {object} defaults configuration object."," * @class CustomEvent"," * @constructor"," */",""," /**"," * The type of event, returned to subscribers when the event fires"," * @property type"," * @type string"," */","","/**"," * By default all custom events are logged in the debug build, set silent"," * to true to disable debug outpu for this event."," * @property silent"," * @type boolean"," */","","Y.CustomEvent = function(type, defaults) {",""," this._kds = Y.CustomEvent.keepDeprecatedSubs;",""," this.id = Y.guid();",""," this.type = type;"," this.silent = this.logSystem = (type === YUI_LOG);",""," if (this._kds) {"," /**"," * The subscribers to this event"," * @property subscribers"," * @type Subscriber {}"," * @deprecated"," */",""," /**"," * 'After' subscribers"," * @property afters"," * @type Subscriber {}"," * @deprecated"," */"," this.subscribers = {};"," this.afters = {};"," }",""," if (defaults) {"," mixConfigs(this, defaults, true);"," }","};","","/**"," * Static flag to enable population of the <a href=\"#property_subscribers\">`subscribers`</a>"," * and <a href=\"#property_subscribers\">`afters`</a> properties held on a `CustomEvent` instance."," *"," * These properties were changed to private properties (`_subscribers` and `_afters`), and"," * converted from objects to arrays for performance reasons."," *"," * Setting this property to true will populate the deprecated `subscribers` and `afters`"," * properties for people who may be using them (which is expected to be rare). There will"," * be a performance hit, compared to the new array based implementation."," *"," * If you are using these deprecated properties for a use case which the public API"," * does not support, please file an enhancement request, and we can provide an alternate"," * public implementation which doesn't have the performance cost required to maintiain the"," * properties as objects."," *"," * @property keepDeprecatedSubs"," * @static"," * @for CustomEvent"," * @type boolean"," * @default false"," * @deprecated"," */","Y.CustomEvent.keepDeprecatedSubs = false;","","Y.CustomEvent.mixConfigs = mixConfigs;","","Y.CustomEvent.prototype = {",""," constructor: Y.CustomEvent,",""," /**"," * Monitor when an event is attached or detached."," *"," * @property monitored"," * @type boolean"," */",""," /**"," * If 0, this event does not broadcast. If 1, the YUI instance is notified"," * every time this event fires. If 2, the YUI instance and the YUI global"," * (if event is enabled on the global) are notified every time this event"," * fires."," * @property broadcast"," * @type int"," */",""," /**"," * Specifies whether this event should be queued when the host is actively"," * processing an event. This will effect exectution order of the callbacks"," * for the various events."," * @property queuable"," * @type boolean"," * @default false"," */",""," /**"," * This event has fired if true"," *"," * @property fired"," * @type boolean"," * @default false;"," */",""," /**"," * An array containing the arguments the custom event"," * was last fired with."," * @property firedWith"," * @type Array"," */",""," /**"," * This event should only fire one time if true, and if"," * it has fired, any new subscribers should be notified"," * immediately."," *"," * @property fireOnce"," * @type boolean"," * @default false;"," */",""," /**"," * fireOnce listeners will fire syncronously unless async"," * is set to true"," * @property async"," * @type boolean"," * @default false"," */",""," /**"," * Flag for stopPropagation that is modified during fire()"," * 1 means to stop propagation to bubble targets. 2 means"," * to also stop additional subscribers on this target."," * @property stopped"," * @type int"," */",""," /**"," * Flag for preventDefault that is modified during fire()."," * if it is not 0, the default behavior for this event"," * @property prevented"," * @type int"," */",""," /**"," * Specifies the host for this custom event. This is used"," * to enable event bubbling"," * @property host"," * @type EventTarget"," */",""," /**"," * The default function to execute after event listeners"," * have fire, but only if the default action was not"," * prevented."," * @property defaultFn"," * @type Function"," */",""," /**"," * The function to execute if a subscriber calls"," * stopPropagation or stopImmediatePropagation"," * @property stoppedFn"," * @type Function"," */",""," /**"," * The function to execute if a subscriber calls"," * preventDefault"," * @property preventedFn"," * @type Function"," */",""," /**"," * The subscribers to this event"," * @property _subscribers"," * @type Subscriber []"," * @private"," */",""," /**"," * 'After' subscribers"," * @property _afters"," * @type Subscriber []"," * @private"," */",""," /**"," * If set to true, the custom event will deliver an EventFacade object"," * that is similar to a DOM event object."," * @property emitFacade"," * @type boolean"," * @default false"," */",""," /**"," * Supports multiple options for listener signatures in order to"," * port YUI 2 apps."," * @property signature"," * @type int"," * @default 9"," */"," signature : YUI3_SIGNATURE,",""," /**"," * The context the the event will fire from by default. Defaults to the YUI"," * instance."," * @property context"," * @type object"," */"," context : Y,",""," /**"," * Specifies whether or not this event's default function"," * can be cancelled by a subscriber by executing preventDefault()"," * on the event facade"," * @property preventable"," * @type boolean"," * @default true"," */"," preventable : true,",""," /**"," * Specifies whether or not a subscriber can stop the event propagation"," * via stopPropagation(), stopImmediatePropagation(), or halt()"," *"," * Events can only bubble if emitFacade is true."," *"," * @property bubbles"," * @type boolean"," * @default true"," */"," bubbles : true,",""," /**"," * Returns the number of subscribers for this event as the sum of the on()"," * subscribers and after() subscribers."," *"," * @method hasSubs"," * @return Number"," */"," hasSubs: function(when) {"," var s = 0,"," a = 0,"," subs = this._subscribers,"," afters = this._afters,"," sib = this.sibling;",""," if (subs) {"," s = subs.length;"," }",""," if (afters) {"," a = afters.length;"," }",""," if (sib) {"," subs = sib._subscribers;"," afters = sib._afters;",""," if (subs) {"," s += subs.length;"," }",""," if (afters) {"," a += afters.length;"," }"," }",""," if (when) {"," return (when === 'after') ? a : s;"," }",""," return (s + a);"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('detach', 'attach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," this.monitored = true;"," var type = this.id + '|' + this.type + '_' + what,"," args = nativeSlice.call(arguments, 0);"," args[0] = type;"," return this.host.on.apply(this.host, args);"," },",""," /**"," * Get all of the subscribers to this event and any sibling event"," * @method getSubs"," * @return {Array} first item is the on subscribers, second the after."," */"," getSubs: function() {",""," var sibling = this.sibling,"," subs = this._subscribers,"," afters = this._afters,"," siblingSubs,"," siblingAfters;",""," if (sibling) {"," siblingSubs = sibling._subscribers;"," siblingAfters = sibling._afters;"," }",""," if (siblingSubs) {"," if (subs) {"," subs = subs.concat(siblingSubs);"," } else {"," subs = siblingSubs.concat();"," }"," } else {"," if (subs) {"," subs = subs.concat();"," } else {"," subs = [];"," }"," }",""," if (siblingAfters) {"," if (afters) {"," afters = afters.concat(siblingAfters);"," } else {"," afters = siblingAfters.concat();"," }"," } else {"," if (afters) {"," afters = afters.concat();"," } else {"," afters = [];"," }"," }",""," return [subs, afters];"," },",""," /**"," * Apply configuration properties. Only applies the CONFIG whitelist"," * @method applyConfig"," * @param o hash of properties to apply."," * @param force {boolean} if true, properties that exist on the event"," * will be overwritten."," */"," applyConfig: function(o, force) {"," mixConfigs(this, o, force);"," },",""," /**"," * Create the Subscription for subscribing function, context, and bound"," * arguments. If this is a fireOnce event, the subscriber is immediately"," * notified."," *"," * @method _on"," * @param fn {Function} Subscription callback"," * @param [context] {Object} Override `this` in the callback"," * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()"," * @param [when] {String} \"after\" to slot into after subscribers"," * @return {EventHandle}"," * @protected"," */"," _on: function(fn, context, args, when) {","",""," var s = new Y.Subscriber(fn, context, args, when),"," firedWith;",""," if (this.fireOnce && this.fired) {",""," firedWith = this.firedWith;",""," // It's a little ugly for this to know about facades,"," // but given the current breakup, not much choice without"," // moving a whole lot of stuff around."," if (this.emitFacade && this._addFacadeToArgs) {"," this._addFacadeToArgs(firedWith);"," }",""," if (this.async) {"," setTimeout(Y.bind(this._notify, this, s, firedWith), 0);"," } else {"," this._notify(s, firedWith);"," }"," }",""," if (when === AFTER) {"," if (!this._afters) {"," this._afters = [];"," }"," this._afters.push(s);"," } else {"," if (!this._subscribers) {"," this._subscribers = [];"," }"," this._subscribers.push(s);"," }",""," if (this._kds) {"," if (when === AFTER) {"," this.afters[s.id] = s;"," } else {"," this.subscribers[s.id] = s;"," }"," }",""," return new Y.EventHandle(this, s);"," },",""," /**"," * Listen for this event"," * @method subscribe"," * @param {Function} fn The function to execute."," * @return {EventHandle} Unsubscribe handle."," * @deprecated use on."," */"," subscribe: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, true);"," },",""," /**"," * Listen for this event"," * @method on"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} An object with a detach method to detch the handler(s)."," */"," on: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;",""," if (this.monitored && this.host) {"," this.host._monitor('attach', this, {"," args: arguments"," });"," }"," return this._on(fn, context, a, true);"," },",""," /**"," * Listen for this event after the normal subscribers have been notified and"," * the default behavior has been applied. If a normal subscriber prevents the"," * default behavior, it also prevents after listeners from firing."," * @method after"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} handle Unsubscribe handle."," */"," after: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, AFTER);"," },",""," /**"," * Detach listeners."," * @method detach"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int} returns the number of subscribers unsubscribed."," */"," detach: function(fn, context) {"," // unsubscribe handle"," if (fn && fn.detach) {"," return fn.detach();"," }",""," var i, s,"," found = 0,"," subs = this._subscribers,"," afters = this._afters;",""," if (subs) {"," for (i = subs.length; i >= 0; i--) {"," s = subs[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, subs, i);"," found++;"," }"," }"," }",""," if (afters) {"," for (i = afters.length; i >= 0; i--) {"," s = afters[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, afters, i);"," found++;"," }"," }"," }",""," return found;"," },",""," /**"," * Detach listeners."," * @method unsubscribe"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int|undefined} returns the number of subscribers unsubscribed."," * @deprecated use detach."," */"," unsubscribe: function() {"," return this.detach.apply(this, arguments);"," },",""," /**"," * Notify a single subscriber"," * @method _notify"," * @param {Subscriber} s the subscriber."," * @param {Array} args the arguments array to apply to the listener."," * @protected"," */"," _notify: function(s, args, ef) {","",""," var ret;",""," ret = s.notify(args, this);",""," if (false === ret || this.stopped > 1) {"," return false;"," }",""," return true;"," },",""," /**"," * Logger abstraction to centralize the application of the silent flag"," * @method log"," * @param {string} msg message to log."," * @param {string} cat log category."," */"," log: function(msg, cat) {"," },",""," /**"," * Notifies the subscribers. The callback functions will be executed"," * from the context specified when the event was created, and with the"," * following parameters:"," * <ul>"," * <li>The type of event</li>"," * <li>All of the arguments fire() was executed with as an array</li>"," * <li>The custom object (if any) that was passed into the subscribe()"," * method</li>"," * </ul>"," * @method fire"," * @param {Object*} arguments an arbitrary set of parameters to pass to"," * the handler."," * @return {boolean} false if one of the subscribers returned false,"," * true otherwise."," *"," */"," fire: function() {",""," // push is the fastest way to go from arguments to arrays"," // for most browsers currently"," // http://jsperf.com/push-vs-concat-vs-slice/2",""," var args = [];"," args.push.apply(args, arguments);",""," return this._fire(args);"," },",""," /**"," * Private internal implementation for `fire`, which is can be used directly by"," * `EventTarget` and other event module classes which have already converted from"," * an `arguments` list to an array, to avoid the repeated overhead."," *"," * @method _fire"," * @private"," * @param {Array} args The array of arguments passed to be passed to handlers."," * @return {boolean} false if one of the subscribers returned false, true otherwise."," */"," _fire: function(args) {",""," if (this.fireOnce && this.fired) {"," return true;"," } else {",""," // this doesn't happen if the event isn't published"," // this.host._monitor('fire', this.type, args);",""," this.fired = true;",""," if (this.fireOnce) {"," this.firedWith = args;"," }",""," if (this.emitFacade) {"," return this.fireComplex(args);"," } else {"," return this.fireSimple(args);"," }"," }"," },",""," /**"," * Set up for notifying subscribers of non-emitFacade events."," *"," * @method fireSimple"," * @param args {Array} Arguments passed to fire()"," * @return Boolean false if a subscriber returned false"," * @protected"," */"," fireSimple: function(args) {"," this.stopped = 0;"," this.prevented = 0;"," if (this.hasSubs()) {"," var subs = this.getSubs();"," this._procSubs(subs[0], args);"," this._procSubs(subs[1], args);"," }"," if (this.broadcast) {"," this._broadcast(args);"," }"," return this.stopped ? false : true;"," },",""," // Requires the event-custom-complex module for full funcitonality."," fireComplex: function(args) {"," args[0] = args[0] || {};"," return this.fireSimple(args);"," },",""," /**"," * Notifies a list of subscribers."," *"," * @method _procSubs"," * @param subs {Array} List of subscribers"," * @param args {Array} Arguments passed to fire()"," * @param ef {}"," * @return Boolean false if a subscriber returns false or stops the event"," * propagation via e.stopPropagation(),"," * e.stopImmediatePropagation(), or e.halt()"," * @private"," */"," _procSubs: function(subs, args, ef) {"," var s, i, l;",""," for (i = 0, l = subs.length; i < l; i++) {"," s = subs[i];"," if (s && s.fn) {"," if (false === this._notify(s, args, ef)) {"," this.stopped = 2;"," }"," if (this.stopped === 2) {"," return false;"," }"," }"," }",""," return true;"," },",""," /**"," * Notifies the YUI instance if the event is configured with broadcast = 1,"," * and both the YUI instance and Y.Global if configured with broadcast = 2."," *"," * @method _broadcast"," * @param args {Array} Arguments sent to fire()"," * @private"," */"," _broadcast: function(args) {"," if (!this.stopped && this.broadcast) {",""," var a = args.concat();"," a.unshift(this.type);",""," if (this.host !== Y) {"," Y.fire.apply(Y, a);"," }",""," if (this.broadcast === 2) {"," Y.Global.fire.apply(Y.Global, a);"," }"," }"," },",""," /**"," * Removes all listeners"," * @method unsubscribeAll"," * @return {int} The number of listeners unsubscribed."," * @deprecated use detachAll."," */"," unsubscribeAll: function() {"," return this.detachAll.apply(this, arguments);"," },",""," /**"," * Removes all listeners"," * @method detachAll"," * @return {int} The number of listeners unsubscribed."," */"," detachAll: function() {"," return this.detach();"," },",""," /**"," * Deletes the subscriber from the internal store of on() and after()"," * subscribers."," *"," * @method _delete"," * @param s subscriber object."," * @param subs (optional) on or after subscriber array"," * @param index (optional) The index found."," * @private"," */"," _delete: function(s, subs, i) {"," var when = s._when;",""," if (!subs) {"," subs = (when === AFTER) ? this._afters : this._subscribers;"," }",""," if (subs) {"," i = YArray.indexOf(subs, s, 0);",""," if (s && subs[i] === s) {"," subs.splice(i, 1);"," }"," }",""," if (this._kds) {"," if (when === AFTER) {"," delete this.afters[s.id];"," } else {"," delete this.subscribers[s.id];"," }"," }",""," if (this.monitored && this.host) {"," this.host._monitor('detach', this, {"," ce: this,"," sub: s"," });"," }",""," if (s) {"," s.deleted = true;"," }"," }","};","/**"," * Stores the subscriber information to be used when the event fires."," * @param {Function} fn The wrapped function to execute."," * @param {Object} context The value of the keyword 'this' in the listener."," * @param {Array} args* 0..n additional arguments to supply the listener."," *"," * @class Subscriber"," * @constructor"," */","Y.Subscriber = function(fn, context, args, when) {",""," /**"," * The callback that will be execute when the event fires"," * This is wrapped by Y.rbind if obj was supplied."," * @property fn"," * @type Function"," */"," this.fn = fn;",""," /**"," * Optional 'this' keyword for the listener"," * @property context"," * @type Object"," */"," this.context = context;",""," /**"," * Unique subscriber id"," * @property id"," * @type String"," */"," this.id = Y.guid();",""," /**"," * Additional arguments to propagate to the subscriber"," * @property args"," * @type Array"," */"," this.args = args;",""," this._when = when;",""," /**"," * Custom events for a given fire transaction."," * @property events"," * @type {EventTarget}"," */"," // this.events = null;",""," /**"," * This listener only reacts to the event once"," * @property once"," */"," // this.once = false;","","};","","Y.Subscriber.prototype = {"," constructor: Y.Subscriber,",""," _notify: function(c, args, ce) {"," if (this.deleted && !this.postponed) {"," if (this.postponed) {"," delete this.fn;"," delete this.context;"," } else {"," delete this.postponed;"," return null;"," }"," }"," var a = this.args, ret;"," switch (ce.signature) {"," case 0:"," ret = this.fn.call(c, ce.type, args, c);"," break;"," case 1:"," ret = this.fn.call(c, args[0] || null, c);"," break;"," default:"," if (a || args) {"," args = args || [];"," a = (a) ? args.concat(a) : args;"," ret = this.fn.apply(c, a);"," } else {"," ret = this.fn.call(c);"," }"," }",""," if (this.once) {"," ce._delete(this);"," }",""," return ret;"," },",""," /**"," * Executes the subscriber."," * @method notify"," * @param args {Array} Arguments array for the subscriber."," * @param ce {CustomEvent} The custom event that sent the notification."," */"," notify: function(args, ce) {"," var c = this.context,"," ret = true;",""," if (!c) {"," c = (ce.contextFn) ? ce.contextFn() : ce.context;"," }",""," // only catch errors if we will not re-throw them."," if (Y.config && Y.config.throwFail) {"," ret = this._notify(c, args, ce);"," } else {"," try {"," ret = this._notify(c, args, ce);"," } catch (e) {"," Y.error(this + ' failed: ' + e.message, e);"," }"," }",""," return ret;"," },",""," /**"," * Returns true if the fn and obj match this objects properties."," * Used by the unsubscribe method to match the right subscriber."," *"," * @method contains"," * @param {Function} fn the function to execute."," * @param {Object} context optional 'this' keyword for the listener."," * @return {boolean} true if the supplied arguments match this"," * subscriber's signature."," */"," contains: function(fn, context) {"," if (context) {"," return ((this.fn === fn) && this.context === context);"," } else {"," return (this.fn === fn);"," }"," },",""," valueOf : function() {"," return this.id;"," }","","};","/**"," * Return value from all subscribe operations"," * @class EventHandle"," * @constructor"," * @param {CustomEvent} evt the custom event."," * @param {Subscriber} sub the subscriber."," */","Y.EventHandle = function(evt, sub) {",""," /**"," * The custom event"," *"," * @property evt"," * @type CustomEvent"," */"," this.evt = evt;",""," /**"," * The subscriber object"," *"," * @property sub"," * @type Subscriber"," */"," this.sub = sub;","};","","Y.EventHandle.prototype = {"," batch: function(f, c) {"," f.call(c || this, this);"," if (Y.Lang.isArray(this.evt)) {"," Y.Array.each(this.evt, function(h) {"," h.batch.call(c || h, f);"," });"," }"," },",""," /**"," * Detaches this subscriber"," * @method detach"," * @return {int} the number of detached listeners"," */"," detach: function() {"," var evt = this.evt, detached = 0, i;"," if (evt) {"," if (Y.Lang.isArray(evt)) {"," for (i = 0; i < evt.length; i++) {"," detached += evt[i].detach();"," }"," } else {"," evt._delete(this.sub);"," detached = 1;"," }",""," }",""," return detached;"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('attach', 'detach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," return this.evt.monitor.apply(this.evt, arguments);"," }","};","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * EventTarget provides the implementation for any object to"," * publish, subscribe and fire to custom events, and also"," * alows other EventTargets to target the object with events"," * sourced from the other object."," * EventTarget is designed to be used with Y.augment to wrap"," * EventCustom in an interface that allows events to be listened to"," * and fired by name. This makes it possible for implementing code to"," * subscribe to an event that either has not been created yet, or will"," * not be created at all."," * @class EventTarget"," * @param opts a configuration object"," * @config emitFacade {boolean} if true, all events will emit event"," * facade payloads by default (default false)"," * @config prefix {String} the prefix to apply to non-prefixed event names"," */","","var L = Y.Lang,"," PREFIX_DELIMITER = ':',"," CATEGORY_DELIMITER = '|',"," AFTER_PREFIX = '~AFTER~',"," WILD_TYPE_RE = /(.*?)(:)(.*?)/,",""," _wildType = Y.cached(function(type) {"," return type.replace(WILD_TYPE_RE, \"*$2$3\");"," }),",""," /**"," * If the instance has a prefix attribute and the"," * event type is not prefixed, the instance prefix is"," * applied to the supplied type."," * @method _getType"," * @private"," */"," _getType = function(type, pre) {",""," if (!pre || !type || type.indexOf(PREFIX_DELIMITER) > -1) {"," return type;"," }",""," return pre + PREFIX_DELIMITER + type;"," },",""," /**"," * Returns an array with the detach key (if provided),"," * and the prefixed event name from _getType"," * Y.on('detachcategory| menu:click', fn)"," * @method _parseType"," * @private"," */"," _parseType = Y.cached(function(type, pre) {",""," var t = type, detachcategory, after, i;",""," if (!L.isString(t)) {"," return t;"," }",""," i = t.indexOf(AFTER_PREFIX);",""," if (i > -1) {"," after = true;"," t = t.substr(AFTER_PREFIX.length);"," }",""," i = t.indexOf(CATEGORY_DELIMITER);",""," if (i > -1) {"," detachcategory = t.substr(0, (i));"," t = t.substr(i+1);"," if (t === '*') {"," t = null;"," }"," }",""," // detach category, full type with instance prefix, is this an after listener, short type"," return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];"," }),",""," ET = function(opts) {",""," var etState = this._yuievt,"," etConfig;",""," if (!etState) {"," etState = this._yuievt = {"," events: {}, // PERF: Not much point instantiating lazily. We're bound to have events"," targets: null, // PERF: Instantiate lazily, if user actually adds target,"," config: {"," host: this,"," context: this"," },"," chain: Y.config.chain"," };"," }",""," etConfig = etState.config;",""," if (opts) {"," mixConfigs(etConfig, opts, true);",""," if (opts.chain !== undefined) {"," etState.chain = opts.chain;"," }",""," if (opts.prefix) {"," etConfig.prefix = opts.prefix;"," }"," }"," };","","ET.prototype = {",""," constructor: ET,",""," /**"," * Listen to a custom event hosted by this object one time."," * This is the equivalent to <code>on</code> except the"," * listener is immediatelly detached when it is executed."," * @method once"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," once: function() {"," var handle = this.on.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Listen to a custom event hosted by this object one time."," * This is the equivalent to <code>after</code> except the"," * listener is immediatelly detached when it is executed."," * @method onceAfter"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," onceAfter: function() {"," var handle = this.after.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Takes the type parameter passed to 'on' and parses out the"," * various pieces that could be included in the type. If the"," * event type is passed without a prefix, it will be expanded"," * to include the prefix one is supplied or the event target"," * is configured with a default prefix."," * @method parseType"," * @param {String} type the type"," * @param {String} [pre=this._yuievt.config.prefix] the prefix"," * @since 3.3.0"," * @return {Array} an array containing:"," * * the detach category, if supplied,"," * * the prefixed event type,"," * * whether or not this is an after listener,"," * * the supplied event type"," */"," parseType: function(type, pre) {"," return _parseType(type, pre || this._yuievt.config.prefix);"," },",""," /**"," * Subscribe a callback function to a custom event fired by this object or"," * from an object that bubbles its events to this object."," *"," * Callback functions for events published with `emitFacade = true` will"," * receive an `EventFacade` as the first argument (typically named \"e\")."," * These callbacks can then call `e.preventDefault()` to disable the"," * behavior published to that event's `defaultFn`. See the `EventFacade`"," * API for all available properties and methods. Subscribers to"," * non-`emitFacade` events will receive the arguments passed to `fire()`"," * after the event name."," *"," * To subscribe to multiple events at once, pass an object as the first"," * argument, where the key:value pairs correspond to the eventName:callback,"," * or pass an array of event names as the first argument to subscribe to"," * all listed events with the same callback."," *"," * Returning `false` from a callback is supported as an alternative to"," * calling `e.preventDefault(); e.stopPropagation();`. However, it is"," * recommended to use the event methods whenever possible."," *"," * @method on"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," on: function(type, fn, context) {",""," var yuievt = this._yuievt,"," parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,"," detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,"," Node = Y.Node, n, domevent, isArr;",""," // full name, args, detachcategory, after"," this._monitor('attach', parts[1], {"," args: arguments,"," category: parts[0],"," after: parts[2]"," });",""," if (L.isObject(type)) {",""," if (L.isFunction(type)) {"," return Y.Do.before.apply(Y.Do, arguments);"," }",""," f = fn;"," c = context;"," args = nativeSlice.call(arguments, 0);"," ret = [];",""," if (L.isArray(type)) {"," isArr = true;"," }",""," after = type._after;"," delete type._after;",""," Y.each(type, function(v, k) {",""," if (L.isObject(v)) {"," f = v.fn || ((L.isFunction(v)) ? v : f);"," c = v.context || c;"," }",""," var nv = (after) ? AFTER_PREFIX : '';",""," args[0] = nv + ((isArr) ? v : k);"," args[1] = f;"," args[2] = c;",""," ret.push(this.on.apply(this, args));",""," }, this);",""," return (yuievt.chain) ? this : new Y.EventHandle(ret);"," }",""," detachcategory = parts[0];"," after = parts[2];"," shorttype = parts[3];",""," // extra redirection so we catch adaptor events too. take a look at this."," if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {"," args = nativeSlice.call(arguments, 0);"," args.splice(2, 0, Node.getDOMNode(this));"," return Y.on.apply(Y, args);"," }",""," type = parts[1];",""," if (Y.instanceOf(this, YUI)) {",""," adapt = Y.Env.evt.plugins[type];"," args = nativeSlice.call(arguments, 0);"," args[0] = shorttype;",""," if (Node) {"," n = args[2];",""," if (Y.instanceOf(n, Y.NodeList)) {"," n = Y.NodeList.getDOMNodes(n);"," } else if (Y.instanceOf(n, Node)) {"," n = Node.getDOMNode(n);"," }",""," domevent = (shorttype in Node.DOM_EVENTS);",""," // Captures both DOM events and event plugins."," if (domevent) {"," args[2] = n;"," }"," }",""," // check for the existance of an event adaptor"," if (adapt) {"," handle = adapt.on.apply(Y, args);"," } else if ((!type) || domevent) {"," handle = Y.Event._attach(args);"," }",""," }",""," if (!handle) {"," ce = yuievt.events[type] || this.publish(type);"," handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);",""," // TODO: More robust regex, accounting for category"," if (type.indexOf(\"*:\") !== -1) {"," this._hasSiblings = true;"," }"," }",""," if (detachcategory) {"," store[detachcategory] = store[detachcategory] || {};"," store[detachcategory][type] = store[detachcategory][type] || [];"," store[detachcategory][type].push(handle);"," }",""," return (yuievt.chain) ? this : handle;",""," },",""," /**"," * subscribe to an event"," * @method subscribe"," * @deprecated use on"," */"," subscribe: function() {"," return this.on.apply(this, arguments);"," },",""," /**"," * Detach one or more listeners the from the specified event"," * @method detach"," * @param type {string|Object} Either the handle to the subscriber or the"," * type of event. If the type"," * is not specified, it will attempt to remove"," * the listener from all hosted events."," * @param fn {Function} The subscribed function to unsubscribe, if not"," * supplied, all subscribers will be removed."," * @param context {Object} The custom object passed to subscribe. This is"," * optional, but if supplied will be used to"," * disambiguate multiple listeners that are the same"," * (e.g., you subscribe many object using a function"," * that lives on the prototype)"," * @return {EventTarget} the host"," */"," detach: function(type, fn, context) {",""," var evts = this._yuievt.events,"," i,"," Node = Y.Node,"," isNode = Node && (Y.instanceOf(this, Node));",""," // detachAll disabled on the Y instance."," if (!type && (this !== Y)) {"," for (i in evts) {"," if (evts.hasOwnProperty(i)) {"," evts[i].detach(fn, context);"," }"," }"," if (isNode) {"," Y.Event.purgeElement(Node.getDOMNode(this));"," }",""," return this;"," }",""," var parts = _parseType(type, this._yuievt.config.prefix),"," detachcategory = L.isArray(parts) ? parts[0] : null,"," shorttype = (parts) ? parts[3] : null,"," adapt, store = Y.Env.evt.handles, detachhost, cat, args,"," ce,",""," keyDetacher = function(lcat, ltype, host) {"," var handles = lcat[ltype], ce, i;"," if (handles) {"," for (i = handles.length - 1; i >= 0; --i) {"," ce = handles[i].evt;"," if (ce.host === host || ce.el === host) {"," handles[i].detach();"," }"," }"," }"," };",""," if (detachcategory) {",""," cat = store[detachcategory];"," type = parts[1];"," detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;",""," if (cat) {"," if (type) {"," keyDetacher(cat, type, detachhost);"," } else {"," for (i in cat) {"," if (cat.hasOwnProperty(i)) {"," keyDetacher(cat, i, detachhost);"," }"," }"," }",""," return this;"," }",""," // If this is an event handle, use it to detach"," } else if (L.isObject(type) && type.detach) {"," type.detach();"," return this;"," // extra redirection so we catch adaptor events too. take a look at this."," } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {"," args = nativeSlice.call(arguments, 0);"," args[2] = Node.getDOMNode(this);"," Y.detach.apply(Y, args);"," return this;"," }",""," adapt = Y.Env.evt.plugins[shorttype];",""," // The YUI instance handles DOM events and adaptors"," if (Y.instanceOf(this, YUI)) {"," args = nativeSlice.call(arguments, 0);"," // use the adaptor specific detach code if"," if (adapt && adapt.detach) {"," adapt.detach.apply(Y, args);"," return this;"," // DOM event fork"," } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {"," args[0] = type;"," Y.Event.detach.apply(Y.Event, args);"," return this;"," }"," }",""," // ce = evts[type];"," ce = evts[parts[1]];"," if (ce) {"," ce.detach(fn, context);"," }",""," return this;"," },",""," /**"," * detach a listener"," * @method unsubscribe"," * @deprecated use detach"," */"," unsubscribe: function() {"," return this.detach.apply(this, arguments);"," },",""," /**"," * Removes all listeners from the specified event. If the event type"," * is not specified, all listeners from all hosted custom events will"," * be removed."," * @method detachAll"," * @param type {String} The type, or name of the event"," */"," detachAll: function(type) {"," return this.detach(type);"," },",""," /**"," * Removes all listeners from the specified event. If the event type"," * is not specified, all listeners from all hosted custom events will"," * be removed."," * @method unsubscribeAll"," * @param type {String} The type, or name of the event"," * @deprecated use detachAll"," */"," unsubscribeAll: function() {"," return this.detachAll.apply(this, arguments);"," },",""," /**"," * Creates a new custom event of the specified type. If a custom event"," * by that name already exists, it will not be re-created. In either"," * case the custom event is returned."," *"," * @method publish"," *"," * @param type {String} the type, or name of the event"," * @param opts {object} optional config params. Valid properties are:"," *"," * <ul>"," * <li>"," * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)"," * </li>"," * <li>"," * 'bubbles': whether or not this event bubbles (true)"," * Events can only bubble if emitFacade is true."," * </li>"," * <li>"," * 'context': the default execution context for the listeners (this)"," * </li>"," * <li>"," * 'defaultFn': the default function to execute when this event fires if preventDefault was not called"," * </li>"," * <li>"," * 'emitFacade': whether or not this event emits a facade (false)"," * </li>"," * <li>"," * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'"," * </li>"," * <li>"," * 'fireOnce': if an event is configured to fire once, new subscribers after"," * the fire will be notified immediately."," * </li>"," * <li>"," * 'async': fireOnce event listeners will fire synchronously if the event has already"," * fired unless async is true."," * </li>"," * <li>"," * 'preventable': whether or not preventDefault() has an effect (true)"," * </li>"," * <li>"," * 'preventedFn': a function that is executed when preventDefault is called"," * </li>"," * <li>"," * 'queuable': whether or not this event can be queued during bubbling (false)"," * </li>"," * <li>"," * 'silent': if silent is true, debug messages are not provided for this event."," * </li>"," * <li>"," * 'stoppedFn': a function that is executed when stopPropagation is called"," * </li>"," *"," * <li>"," * 'monitored': specifies whether or not this event should send notifications about"," * when the event has been attached, detached, or published."," * </li>"," * <li>"," * 'type': the event type (valid option if not provided as the first parameter to publish)"," * </li>"," * </ul>"," *"," * @return {CustomEvent} the custom event"," *"," */"," publish: function(type, opts) {",""," var ret,"," etState = this._yuievt,"," etConfig = etState.config,"," pre = etConfig.prefix;",""," if (typeof type === \"string\") {"," if (pre) {"," type = _getType(type, pre);"," }"," ret = this._publish(type, etConfig, opts);"," } else {"," ret = {};",""," Y.each(type, function(v, k) {"," if (pre) {"," k = _getType(k, pre);"," }"," ret[k] = this._publish(k, etConfig, v || opts);"," }, this);",""," }",""," return ret;"," },",""," /**"," * Returns the fully qualified type, given a short type string."," * That is, returns \"foo:bar\" when given \"bar\" if \"foo\" is the configured prefix."," *"," * NOTE: This method, unlike _getType, does no checking of the value passed in, and"," * is designed to be used with the low level _publish() method, for critical path"," * implementations which need to fast-track publish for performance reasons."," *"," * @method _getFullType"," * @private"," * @param {String} type The short type to prefix"," * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in"," */"," _getFullType : function(type) {",""," var pre = this._yuievt.config.prefix;",""," if (pre) {"," return pre + PREFIX_DELIMITER + type;"," } else {"," return type;"," }"," },",""," /**"," * The low level event publish implementation. It expects all the massaging to have been done"," * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast"," * path publish, which can be used by critical code paths to improve performance."," *"," * @method _publish"," * @private"," * @param {String} fullType The prefixed type of the event to publish."," * @param {Object} etOpts The EventTarget specific configuration to mix into the published event."," * @param {Object} ceOpts The publish specific configuration to mix into the published event."," * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will"," * be the default `CustomEvent` instance, and can be configured independently."," */"," _publish : function(fullType, etOpts, ceOpts) {",""," var ce,"," etState = this._yuievt,"," etConfig = etState.config,"," host = etConfig.host,"," context = etConfig.context,"," events = etState.events;",""," ce = events[fullType];",""," // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight."," if ((etConfig.monitored && !ce) || (ce && ce.monitored)) {"," this._monitor('publish', fullType, {"," args: arguments"," });"," }",""," if (!ce) {"," // Publish event"," ce = events[fullType] = new Y.CustomEvent(fullType, etOpts);",""," if (!etOpts) {"," ce.host = host;"," ce.context = context;"," }"," }",""," if (ceOpts) {"," mixConfigs(ce, ceOpts, true);"," }",""," return ce;"," },",""," /**"," * This is the entry point for the event monitoring system."," * You can monitor 'attach', 'detach', 'fire', and 'publish'."," * When configured, these events generate an event. click ->"," * click_attach, click_detach, click_publish -- these can"," * be subscribed to like other events to monitor the event"," * system. Inividual published events can have monitoring"," * turned on or off (publish can't be turned off before it"," * it published) by setting the events 'monitor' config."," *"," * @method _monitor"," * @param what {String} 'attach', 'detach', 'fire', or 'publish'"," * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object."," * @param o {Object} Information about the event interaction, such as"," * fire() args, subscription category, publish config"," * @private"," */"," _monitor: function(what, eventType, o) {"," var monitorevt, ce, type;",""," if (eventType) {"," if (typeof eventType === \"string\") {"," type = eventType;"," ce = this.getEvent(eventType, true);"," } else {"," ce = eventType;"," type = eventType.type;"," }",""," if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {"," monitorevt = type + '_' + what;"," o.monitored = what;"," this.fire.call(this, monitorevt, o);"," }"," }"," },",""," /**"," * Fire a custom event by name. The callback functions will be executed"," * from the context specified when the event was created, and with the"," * following parameters."," *"," * The first argument is the event type, and any additional arguments are"," * passed to the listeners as parameters. If the first of these is an"," * object literal, and the event is configured to emit an event facade,"," * that object is mixed into the event facade and the facade is provided"," * in place of the original object."," *"," * If the custom event object hasn't been created, then the event hasn't"," * been published and it has no subscribers. For performance sake, we"," * immediate exit in this case. This means the event won't bubble, so"," * if the intention is that a bubble target be notified, the event must"," * be published on this object first."," *"," * @method fire"," * @param type {String|Object} The type of the event, or an object that contains"," * a 'type' property."," * @param arguments {Object*} an arbitrary set of parameters to pass to"," * the handler. If the first of these is an object literal and the event is"," * configured to emit an event facade, the event facade will replace that"," * parameter after the properties the object literal contains are copied to"," * the event facade."," * @return {Boolean} True if the whole lifecycle of the event went through,"," * false if at any point the event propagation was halted."," */"," fire: function(type) {",""," var typeIncluded = (typeof type === \"string\"),"," argCount = arguments.length,"," t = type,"," yuievt = this._yuievt,"," etConfig = yuievt.config,"," pre = etConfig.prefix,"," ret,"," ce,"," ce2,"," args;",""," if (typeIncluded && argCount <= 3) {",""," // PERF: Try to avoid slice/iteration for the common signatures",""," // Most common"," if (argCount === 2) {"," args = [arguments[1]]; // fire(\"foo\", {})"," } else if (argCount === 3) {"," args = [arguments[1], arguments[2]]; // fire(\"foo\", {}, opts)"," } else {"," args = []; // fire(\"foo\")"," }",""," } else {"," args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0));"," }",""," if (!typeIncluded) {"," t = (type && type.type);"," }",""," if (pre) {"," t = _getType(t, pre);"," }",""," ce = yuievt.events[t];",""," if (this._hasSiblings) {"," ce2 = this.getSibling(t, ce);",""," if (ce2 && !ce) {"," ce = this.publish(t);"," }"," }",""," // PERF: trying to avoid function call, since this is a critical path"," if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {"," this._monitor('fire', (ce || t), {"," args: args"," });"," }",""," // this event has not been published or subscribed to"," if (!ce) {"," if (yuievt.hasTargets) {"," return this.bubble({ type: t }, args, this);"," }",""," // otherwise there is nothing to be done"," ret = true;"," } else {",""," if (ce2) {"," ce.sibling = ce2;"," }",""," ret = ce._fire(args);"," }",""," return (yuievt.chain) ? this : ret;"," },",""," getSibling: function(type, ce) {"," var ce2;",""," // delegate to *:type events if there are subscribers"," if (type.indexOf(PREFIX_DELIMITER) > -1) {"," type = _wildType(type);"," ce2 = this.getEvent(type, true);"," if (ce2) {"," ce2.applyConfig(ce);"," ce2.bubbles = false;"," ce2.broadcast = 0;"," }"," }",""," return ce2;"," },",""," /**"," * Returns the custom event of the provided type has been created, a"," * falsy value otherwise"," * @method getEvent"," * @param type {String} the type, or name of the event"," * @param prefixed {String} if true, the type is prefixed already"," * @return {CustomEvent} the custom event or null"," */"," getEvent: function(type, prefixed) {"," var pre, e;",""," if (!prefixed) {"," pre = this._yuievt.config.prefix;"," type = (pre) ? _getType(type, pre) : type;"," }"," e = this._yuievt.events;"," return e[type] || null;"," },",""," /**"," * Subscribe to a custom event hosted by this object. The"," * supplied callback will execute after any listeners add"," * via the subscribe method, and after the default function,"," * if configured for the event, has executed."," *"," * @method after"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," after: function(type, fn) {",""," var a = nativeSlice.call(arguments, 0);",""," switch (L.type(type)) {"," case 'function':"," return Y.Do.after.apply(Y.Do, arguments);"," case 'array':"," // YArray.each(a[0], function(v) {"," // v = AFTER_PREFIX + v;"," // });"," // break;"," case 'object':"," a[0]._after = true;"," break;"," default:"," a[0] = AFTER_PREFIX + type;"," }",""," return this.on.apply(this, a);",""," },",""," /**"," * Executes the callback before a DOM event, custom event"," * or method. If the first argument is a function, it"," * is assumed the target is a method. For DOM and custom"," * events, this is an alias for Y.on."," *"," * For DOM and custom events:"," * type, callback, context, 0-n arguments"," *"," * For methods:"," * callback, object (method host), methodName, context, 0-n arguments"," *"," * @method before"," * @return detach handle"," */"," before: function() {"," return this.on.apply(this, arguments);"," }","","};","","Y.EventTarget = ET;","","// make Y an event target","Y.mix(Y, ET.prototype);","ET.call(Y, { bubbles: false });","","YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();","","/**"," * Hosts YUI page level events. This is where events bubble to"," * when the broadcast config is set to 2. This property is"," * only available if the custom event module is loaded."," * @property Global"," * @type EventTarget"," * @for YUI"," */","Y.Global = YUI.Env.globalEvents;","","// @TODO implement a global namespace function on Y.Global?","","/**","`Y.on()` can do many things:","","<ul>"," <li>Subscribe to custom events `publish`ed and `fire`d from Y</li>"," <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and"," `fire`d from any object in the YUI instance sandbox</li>"," <li>Subscribe to DOM events</li>"," <li>Subscribe to the execution of a method on any object, effectively"," treating that method as an event</li>","</ul>","","For custom event subscriptions, pass the custom event name as the first argument","and callback as the second. The `this` object in the callback will be `Y` unless","an override is passed as the third argument.",""," Y.on('io:complete', function () {"," Y.MyApp.updateStatus('Transaction complete');"," });","","To subscribe to DOM events, pass the name of a DOM event as the first argument","and a CSS selector string as the third argument after the callback function.","Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,","array, or simply omitted (the default is the `window` object).",""," Y.on('click', function (e) {"," e.preventDefault();",""," // proceed with ajax form submission"," var url = this.get('action');"," ..."," }, '#my-form');","","The `this` object in DOM event callbacks will be the `Node` targeted by the CSS","selector or other identifier.","","`on()` subscribers for DOM events or custom events `publish`ed with a","`defaultFn` can prevent the default behavior with `e.preventDefault()` from the","event object passed as the first parameter to the subscription callback.","","To subscribe to the execution of an object method, pass arguments corresponding to the call signature for","<a href=\"../classes/Do.html#methods_before\">`Y.Do.before(...)`</a>.","","NOTE: The formal parameter list below is for events, not for function","injection. See `Y.Do.before` for that signature.","","@method on","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@see Do.before","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `on()`, except that","the listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see on","@method once","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `once()`, except, like `after()`,","the subscription callback executes after all `on()` subscribers and the event's","`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase","subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`","subscribers will execute.","","The listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see once","@method onceAfter","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Like `on()`, this method creates a subscription to a custom event or to the","execution of a method on an object.","","For events, `after()` subscribers are executed after the event's","`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","NOTE: The subscription signature shown is for events, not for function","injection. See <a href=\"../classes/Do.html#methods_after\">`Y.Do.after`</a>","for that signature.","","@see on","@see Do.after","@method after","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [args*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","","}, '@VERSION@', {\"requires\": [\"oop\"]});","","}());"]}; } var __cov_0ShtDtxkEapLmfzOgrY8Kw = __coverage__['build/event-custom-base/event-custom-base.js']; __cov_0ShtDtxkEapLmfzOgrY8Kw.s['1']++;YUI.add('event-custom-base',function(Y,NAME){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['1']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['2']++;Y.Env.evt={handles:{},plugins:{}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['3']++;var DO_BEFORE=0,DO_AFTER=1,DO={objs:null,before:function(fn,obj,sFn,c){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['2']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['4']++;var f=fn,a;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['5']++;if(c){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['1'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['6']++;a=[fn,c].concat(Y.Array(arguments,4,true));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['7']++;f=Y.rbind.apply(Y,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['1'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['8']++;return this._inject(DO_BEFORE,f,obj,sFn);},after:function(fn,obj,sFn,c){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['3']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['9']++;var f=fn,a;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['10']++;if(c){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['2'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['11']++;a=[fn,c].concat(Y.Array(arguments,4,true));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['12']++;f=Y.rbind.apply(Y,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['2'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['13']++;return this._inject(DO_AFTER,f,obj,sFn);},_inject:function(when,fn,obj,sFn){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['4']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['14']++;var id=Y.stamp(obj),o,sid;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['15']++;if(!obj._yuiaop){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['3'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['16']++;obj._yuiaop={};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['3'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['17']++;o=obj._yuiaop;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['18']++;if(!o[sFn]){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['4'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['19']++;o[sFn]=new Y.Do.Method(obj,sFn);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['20']++;obj[sFn]=function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['5']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['21']++;return o[sFn].exec.apply(o[sFn],arguments);};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['4'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['22']++;sid=id+Y.stamp(fn)+sFn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['23']++;o[sFn].register(sid,fn,when);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['24']++;return new Y.EventHandle(o[sFn],sid);},detach:function(handle){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['6']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['25']++;if(handle.detach){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['5'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['26']++;handle.detach();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['5'][1]++;}}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['27']++;Y.Do=DO;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['28']++;DO.Method=function(obj,sFn){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['7']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['29']++;this.obj=obj;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['30']++;this.methodName=sFn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['31']++;this.method=obj[sFn];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['32']++;this.before={};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['33']++;this.after={};};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['34']++;DO.Method.prototype.register=function(sid,fn,when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['8']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['35']++;if(when){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['6'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['36']++;this.after[sid]=fn;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['6'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['37']++;this.before[sid]=fn;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['38']++;DO.Method.prototype._delete=function(sid){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['9']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['39']++;delete this.before[sid];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['40']++;delete this.after[sid];};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['41']++;DO.Method.prototype.exec=function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['10']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['42']++;var args=Y.Array(arguments,0,true),i,ret,newRet,bf=this.before,af=this.after,prevented=false;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['43']++;for(i in bf){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['44']++;if(bf.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['7'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['45']++;ret=bf[i].apply(this.obj,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['46']++;if(ret){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['8'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['47']++;switch(ret.constructor){case DO.Halt:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['48']++;return ret.retVal;case DO.AlterArgs:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['49']++;args=ret.newArgs;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['50']++;break;case DO.Prevent:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][2]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['51']++;prevented=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['52']++;break;default:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][3]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['8'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['7'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['53']++;if(!prevented){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['10'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['54']++;ret=this.method.apply(this.obj,args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['10'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['55']++;DO.originalRetVal=ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['56']++;DO.currentRetVal=ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['57']++;for(i in af){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['58']++;if(af.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['11'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['59']++;newRet=af[i].apply(this.obj,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['60']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['13'][0]++,newRet)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['13'][1]++,newRet.constructor===DO.Halt)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['12'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['61']++;return newRet.retVal;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['12'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['62']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['15'][0]++,newRet)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['15'][1]++,newRet.constructor===DO.AlterReturn)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['14'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['63']++;ret=newRet.newRetVal;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['64']++;DO.currentRetVal=ret;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['14'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['11'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['65']++;return ret;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['66']++;DO.AlterArgs=function(msg,newArgs){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['11']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['67']++;this.msg=msg;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['68']++;this.newArgs=newArgs;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['69']++;DO.AlterReturn=function(msg,newRetVal){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['12']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['70']++;this.msg=msg;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['71']++;this.newRetVal=newRetVal;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['72']++;DO.Halt=function(msg,retVal){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['13']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['73']++;this.msg=msg;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['74']++;this.retVal=retVal;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['75']++;DO.Prevent=function(msg){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['14']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['76']++;this.msg=msg;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['77']++;DO.Error=DO.Halt;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['78']++;var YArray=Y.Array,AFTER='after',CONFIGS=['broadcast','monitored','bubbles','context','contextFn','currentTarget','defaultFn','defaultTargetOnly','details','emitFacade','fireOnce','async','host','preventable','preventedFn','queuable','silent','stoppedFn','target','type'],CONFIGS_HASH=YArray.hash(CONFIGS),nativeSlice=Array.prototype.slice,YUI3_SIGNATURE=9,YUI_LOG='yui:log',mixConfigs=function(r,s,ov){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['15']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['79']++;var p;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['80']++;for(p in s){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['81']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['17'][0]++,CONFIGS_HASH[p])&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['17'][1]++,ov)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['17'][2]++,!(p in r)))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['16'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['82']++;r[p]=s[p];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['16'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['83']++;return r;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['84']++;Y.CustomEvent=function(type,defaults){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['16']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['85']++;this._kds=Y.CustomEvent.keepDeprecatedSubs;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['86']++;this.id=Y.guid();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['87']++;this.type=type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['88']++;this.silent=this.logSystem=type===YUI_LOG;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['89']++;if(this._kds){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['18'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['90']++;this.subscribers={};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['91']++;this.afters={};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['18'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['92']++;if(defaults){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['19'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['93']++;mixConfigs(this,defaults,true);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['19'][1]++;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['94']++;Y.CustomEvent.keepDeprecatedSubs=false;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['95']++;Y.CustomEvent.mixConfigs=mixConfigs;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['96']++;Y.CustomEvent.prototype={constructor:Y.CustomEvent,signature:YUI3_SIGNATURE,context:Y,preventable:true,bubbles:true,hasSubs:function(when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['17']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['97']++;var s=0,a=0,subs=this._subscribers,afters=this._afters,sib=this.sibling;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['98']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['20'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['99']++;s=subs.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['20'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['100']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['21'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['101']++;a=afters.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['21'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['102']++;if(sib){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['22'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['103']++;subs=sib._subscribers;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['104']++;afters=sib._afters;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['105']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['23'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['106']++;s+=subs.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['23'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['107']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['24'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['108']++;a+=afters.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['24'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['22'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['109']++;if(when){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['25'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['110']++;return when==='after'?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['26'][0]++,a):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['26'][1]++,s);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['25'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['111']++;return s+a;},monitor:function(what){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['18']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['112']++;this.monitored=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['113']++;var type=this.id+'|'+this.type+'_'+what,args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['114']++;args[0]=type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['115']++;return this.host.on.apply(this.host,args);},getSubs:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['19']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['116']++;var sibling=this.sibling,subs=this._subscribers,afters=this._afters,siblingSubs,siblingAfters;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['117']++;if(sibling){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['27'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['118']++;siblingSubs=sibling._subscribers;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['119']++;siblingAfters=sibling._afters;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['27'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['120']++;if(siblingSubs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['28'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['121']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['29'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['122']++;subs=subs.concat(siblingSubs);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['29'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['123']++;subs=siblingSubs.concat();}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['28'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['124']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['30'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['125']++;subs=subs.concat();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['30'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['126']++;subs=[];}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['127']++;if(siblingAfters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['31'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['128']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['32'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['129']++;afters=afters.concat(siblingAfters);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['32'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['130']++;afters=siblingAfters.concat();}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['31'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['131']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['33'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['132']++;afters=afters.concat();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['33'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['133']++;afters=[];}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['134']++;return[subs,afters];},applyConfig:function(o,force){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['20']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['135']++;mixConfigs(this,o,force);},_on:function(fn,context,args,when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['21']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['136']++;var s=new Y.Subscriber(fn,context,args,when),firedWith;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['137']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['35'][0]++,this.fireOnce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['35'][1]++,this.fired)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['34'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['138']++;firedWith=this.firedWith;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['139']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['37'][0]++,this.emitFacade)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['37'][1]++,this._addFacadeToArgs)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['36'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['140']++;this._addFacadeToArgs(firedWith);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['36'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['141']++;if(this.async){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['38'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['142']++;setTimeout(Y.bind(this._notify,this,s,firedWith),0);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['38'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['143']++;this._notify(s,firedWith);}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['34'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['144']++;if(when===AFTER){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['39'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['145']++;if(!this._afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['40'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['146']++;this._afters=[];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['40'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['147']++;this._afters.push(s);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['39'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['148']++;if(!this._subscribers){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['41'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['149']++;this._subscribers=[];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['41'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['150']++;this._subscribers.push(s);}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['151']++;if(this._kds){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['42'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['152']++;if(when===AFTER){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['43'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['153']++;this.afters[s.id]=s;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['43'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['154']++;this.subscribers[s.id]=s;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['42'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['155']++;return new Y.EventHandle(this,s);},subscribe:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['22']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['156']++;var a=arguments.length>2?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['44'][0]++,nativeSlice.call(arguments,2)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['44'][1]++,null);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['157']++;return this._on(fn,context,a,true);},on:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['23']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['158']++;var a=arguments.length>2?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['45'][0]++,nativeSlice.call(arguments,2)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['45'][1]++,null);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['159']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['47'][0]++,this.monitored)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['47'][1]++,this.host)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['46'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['160']++;this.host._monitor('attach',this,{args:arguments});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['46'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['161']++;return this._on(fn,context,a,true);},after:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['24']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['162']++;var a=arguments.length>2?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['48'][0]++,nativeSlice.call(arguments,2)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['48'][1]++,null);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['163']++;return this._on(fn,context,a,AFTER);},detach:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['25']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['164']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['50'][0]++,fn)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['50'][1]++,fn.detach)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['49'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['165']++;return fn.detach();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['49'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['166']++;var i,s,found=0,subs=this._subscribers,afters=this._afters;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['167']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['51'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['168']++;for(i=subs.length;i>=0;i--){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['169']++;s=subs[i];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['170']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['53'][0]++,s)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['53'][1]++,!fn)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['53'][2]++,fn===s.fn))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['52'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['171']++;this._delete(s,subs,i);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['172']++;found++;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['52'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['51'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['173']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['54'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['174']++;for(i=afters.length;i>=0;i--){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['175']++;s=afters[i];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['176']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['56'][0]++,s)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['56'][1]++,!fn)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['56'][2]++,fn===s.fn))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['55'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['177']++;this._delete(s,afters,i);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['178']++;found++;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['55'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['54'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['179']++;return found;},unsubscribe:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['26']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['180']++;return this.detach.apply(this,arguments);},_notify:function(s,args,ef){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['27']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['181']++;var ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['182']++;ret=s.notify(args,this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['183']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['58'][0]++,false===ret)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['58'][1]++,this.stopped>1)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['57'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['184']++;return false;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['57'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['185']++;return true;},log:function(msg,cat){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['28']++;},fire:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['29']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['186']++;var args=[];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['187']++;args.push.apply(args,arguments);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['188']++;return this._fire(args);},_fire:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['30']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['189']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['60'][0]++,this.fireOnce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['60'][1]++,this.fired)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['59'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['190']++;return true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['59'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['191']++;this.fired=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['192']++;if(this.fireOnce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['61'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['193']++;this.firedWith=args;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['61'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['194']++;if(this.emitFacade){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['62'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['195']++;return this.fireComplex(args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['62'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['196']++;return this.fireSimple(args);}}},fireSimple:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['31']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['197']++;this.stopped=0;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['198']++;this.prevented=0;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['199']++;if(this.hasSubs()){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['63'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['200']++;var subs=this.getSubs();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['201']++;this._procSubs(subs[0],args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['202']++;this._procSubs(subs[1],args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['63'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['203']++;if(this.broadcast){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['64'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['204']++;this._broadcast(args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['64'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['205']++;return this.stopped?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['65'][0]++,false):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['65'][1]++,true);},fireComplex:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['32']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['206']++;args[0]=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['66'][0]++,args[0])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['66'][1]++,{});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['207']++;return this.fireSimple(args);},_procSubs:function(subs,args,ef){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['33']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['208']++;var s,i,l;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['209']++;for(i=0,l=subs.length;i<l;i++){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['210']++;s=subs[i];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['211']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['68'][0]++,s)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['68'][1]++,s.fn)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['67'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['212']++;if(false===this._notify(s,args,ef)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['69'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['213']++;this.stopped=2;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['69'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['214']++;if(this.stopped===2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['70'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['215']++;return false;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['70'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['67'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['216']++;return true;},_broadcast:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['34']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['217']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['72'][0]++,!this.stopped)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['72'][1]++,this.broadcast)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['71'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['218']++;var a=args.concat();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['219']++;a.unshift(this.type);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['220']++;if(this.host!==Y){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['73'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['221']++;Y.fire.apply(Y,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['73'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['222']++;if(this.broadcast===2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['74'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['223']++;Y.Global.fire.apply(Y.Global,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['74'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['71'][1]++;}},unsubscribeAll:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['35']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['224']++;return this.detachAll.apply(this,arguments);},detachAll:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['36']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['225']++;return this.detach();},_delete:function(s,subs,i){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['37']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['226']++;var when=s._when;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['227']++;if(!subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['75'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['228']++;subs=when===AFTER?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['76'][0]++,this._afters):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['76'][1]++,this._subscribers);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['75'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['229']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['77'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['230']++;i=YArray.indexOf(subs,s,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['231']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['79'][0]++,s)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['79'][1]++,subs[i]===s)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['78'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['232']++;subs.splice(i,1);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['78'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['77'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['233']++;if(this._kds){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['80'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['234']++;if(when===AFTER){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['81'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['235']++;delete this.afters[s.id];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['81'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['236']++;delete this.subscribers[s.id];}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['80'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['237']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['83'][0]++,this.monitored)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['83'][1]++,this.host)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['82'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['238']++;this.host._monitor('detach',this,{ce:this,sub:s});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['82'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['239']++;if(s){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['84'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['240']++;s.deleted=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['84'][1]++;}}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['241']++;Y.Subscriber=function(fn,context,args,when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['38']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['242']++;this.fn=fn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['243']++;this.context=context;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['244']++;this.id=Y.guid();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['245']++;this.args=args;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['246']++;this._when=when;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['247']++;Y.Subscriber.prototype={constructor:Y.Subscriber,_notify:function(c,args,ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['39']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['248']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['86'][0]++,this.deleted)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['86'][1]++,!this.postponed)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['85'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['249']++;if(this.postponed){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['87'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['250']++;delete this.fn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['251']++;delete this.context;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['87'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['252']++;delete this.postponed;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['253']++;return null;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['85'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['254']++;var a=this.args,ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['255']++;switch(ce.signature){case 0:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['88'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['256']++;ret=this.fn.call(c,ce.type,args,c);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['257']++;break;case 1:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['88'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['258']++;ret=this.fn.call(c,(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['89'][0]++,args[0])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['89'][1]++,null),c);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['259']++;break;default:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['88'][2]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['260']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['91'][0]++,a)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['91'][1]++,args)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['90'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['261']++;args=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['92'][0]++,args)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['92'][1]++,[]);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['262']++;a=a?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['93'][0]++,args.concat(a)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['93'][1]++,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['263']++;ret=this.fn.apply(c,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['90'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['264']++;ret=this.fn.call(c);}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['265']++;if(this.once){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['94'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['266']++;ce._delete(this);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['94'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['267']++;return ret;},notify:function(args,ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['40']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['268']++;var c=this.context,ret=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['269']++;if(!c){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['95'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['270']++;c=ce.contextFn?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['96'][0]++,ce.contextFn()):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['96'][1]++,ce.context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['95'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['271']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['98'][0]++,Y.config)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['98'][1]++,Y.config.throwFail)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['97'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['272']++;ret=this._notify(c,args,ce);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['97'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['273']++;try{__cov_0ShtDtxkEapLmfzOgrY8Kw.s['274']++;ret=this._notify(c,args,ce);}catch(e){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['275']++;Y.error(this+' failed: '+e.message,e);}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['276']++;return ret;},contains:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['41']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['277']++;if(context){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['99'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['278']++;return(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['100'][0]++,this.fn===fn)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['100'][1]++,this.context===context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['99'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['279']++;return this.fn===fn;}},valueOf:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['42']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['280']++;return this.id;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['281']++;Y.EventHandle=function(evt,sub){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['43']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['282']++;this.evt=evt;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['283']++;this.sub=sub;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['284']++;Y.EventHandle.prototype={batch:function(f,c){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['44']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['285']++;f.call((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['101'][0]++,c)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['101'][1]++,this),this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['286']++;if(Y.Lang.isArray(this.evt)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['102'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['287']++;Y.Array.each(this.evt,function(h){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['45']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['288']++;h.batch.call((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['103'][0]++,c)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['103'][1]++,h),f);});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['102'][1]++;}},detach:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['46']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['289']++;var evt=this.evt,detached=0,i;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['290']++;if(evt){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['104'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['291']++;if(Y.Lang.isArray(evt)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['105'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['292']++;for(i=0;i<evt.length;i++){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['293']++;detached+=evt[i].detach();}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['105'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['294']++;evt._delete(this.sub);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['295']++;detached=1;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['104'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['296']++;return detached;},monitor:function(what){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['47']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['297']++;return this.evt.monitor.apply(this.evt,arguments);}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['298']++;var L=Y.Lang,PREFIX_DELIMITER=':',CATEGORY_DELIMITER='|',AFTER_PREFIX='~AFTER~',WILD_TYPE_RE=/(.*?)(:)(.*?)/,_wildType=Y.cached(function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['48']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['299']++;return type.replace(WILD_TYPE_RE,'*$2$3');}),_getType=function(type,pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['49']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['300']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['107'][0]++,!pre)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['107'][1]++,!type)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['107'][2]++,type.indexOf(PREFIX_DELIMITER)>-1)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['106'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['301']++;return type;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['106'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['302']++;return pre+PREFIX_DELIMITER+type;},_parseType=Y.cached(function(type,pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['50']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['303']++;var t=type,detachcategory,after,i;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['304']++;if(!L.isString(t)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['108'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['305']++;return t;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['108'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['306']++;i=t.indexOf(AFTER_PREFIX);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['307']++;if(i>-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['109'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['308']++;after=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['309']++;t=t.substr(AFTER_PREFIX.length);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['109'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['310']++;i=t.indexOf(CATEGORY_DELIMITER);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['311']++;if(i>-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['110'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['312']++;detachcategory=t.substr(0,i);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['313']++;t=t.substr(i+1);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['314']++;if(t==='*'){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['111'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['315']++;t=null;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['111'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['110'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['316']++;return[detachcategory,pre?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['112'][0]++,_getType(t,pre)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['112'][1]++,t),after,t];}),ET=function(opts){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['51']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['317']++;var etState=this._yuievt,etConfig;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['318']++;if(!etState){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['113'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['319']++;etState=this._yuievt={events:{},targets:null,config:{host:this,context:this},chain:Y.config.chain};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['113'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['320']++;etConfig=etState.config;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['321']++;if(opts){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['114'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['322']++;mixConfigs(etConfig,opts,true);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['323']++;if(opts.chain!==undefined){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['115'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['324']++;etState.chain=opts.chain;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['115'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['325']++;if(opts.prefix){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['116'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['326']++;etConfig.prefix=opts.prefix;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['116'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['114'][1]++;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['327']++;ET.prototype={constructor:ET,once:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['52']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['328']++;var handle=this.on.apply(this,arguments);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['329']++;handle.batch(function(hand){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['53']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['330']++;if(hand.sub){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['117'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['331']++;hand.sub.once=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['117'][1]++;}});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['332']++;return handle;},onceAfter:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['54']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['333']++;var handle=this.after.apply(this,arguments);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['334']++;handle.batch(function(hand){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['55']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['335']++;if(hand.sub){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['118'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['336']++;hand.sub.once=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['118'][1]++;}});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['337']++;return handle;},parseType:function(type,pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['56']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['338']++;return _parseType(type,(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['119'][0]++,pre)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['119'][1]++,this._yuievt.config.prefix));},on:function(type,fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['57']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['339']++;var yuievt=this._yuievt,parts=_parseType(type,yuievt.config.prefix),f,c,args,ret,ce,detachcategory,handle,store=Y.Env.evt.handles,after,adapt,shorttype,Node=Y.Node,n,domevent,isArr;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['340']++;this._monitor('attach',parts[1],{args:arguments,category:parts[0],after:parts[2]});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['341']++;if(L.isObject(type)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['120'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['342']++;if(L.isFunction(type)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['121'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['343']++;return Y.Do.before.apply(Y.Do,arguments);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['121'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['344']++;f=fn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['345']++;c=context;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['346']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['347']++;ret=[];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['348']++;if(L.isArray(type)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['122'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['349']++;isArr=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['122'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['350']++;after=type._after;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['351']++;delete type._after;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['352']++;Y.each(type,function(v,k){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['58']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['353']++;if(L.isObject(v)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['123'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['354']++;f=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['124'][0]++,v.fn)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['124'][1]++,L.isFunction(v)?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['125'][0]++,v):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['125'][1]++,f));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['355']++;c=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['126'][0]++,v.context)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['126'][1]++,c);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['123'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['356']++;var nv=after?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['127'][0]++,AFTER_PREFIX):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['127'][1]++,'');__cov_0ShtDtxkEapLmfzOgrY8Kw.s['357']++;args[0]=nv+(isArr?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['128'][0]++,v):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['128'][1]++,k));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['358']++;args[1]=f;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['359']++;args[2]=c;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['360']++;ret.push(this.on.apply(this,args));},this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['361']++;return yuievt.chain?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['129'][0]++,this):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['129'][1]++,new Y.EventHandle(ret));}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['120'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['362']++;detachcategory=parts[0];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['363']++;after=parts[2];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['364']++;shorttype=parts[3];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['365']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['131'][0]++,Node)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['131'][1]++,Y.instanceOf(this,Node))&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['131'][2]++,shorttype in Node.DOM_EVENTS)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['130'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['366']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['367']++;args.splice(2,0,Node.getDOMNode(this));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['368']++;return Y.on.apply(Y,args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['130'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['369']++;type=parts[1];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['370']++;if(Y.instanceOf(this,YUI)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['132'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['371']++;adapt=Y.Env.evt.plugins[type];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['372']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['373']++;args[0]=shorttype;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['374']++;if(Node){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['133'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['375']++;n=args[2];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['376']++;if(Y.instanceOf(n,Y.NodeList)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['134'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['377']++;n=Y.NodeList.getDOMNodes(n);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['134'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['378']++;if(Y.instanceOf(n,Node)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['135'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['379']++;n=Node.getDOMNode(n);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['135'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['380']++;domevent=shorttype in Node.DOM_EVENTS;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['381']++;if(domevent){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['136'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['382']++;args[2]=n;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['136'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['133'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['383']++;if(adapt){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['137'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['384']++;handle=adapt.on.apply(Y,args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['137'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['385']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['139'][0]++,!type)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['139'][1]++,domevent)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['138'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['386']++;handle=Y.Event._attach(args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['138'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['132'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['387']++;if(!handle){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['140'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['388']++;ce=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['141'][0]++,yuievt.events[type])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['141'][1]++,this.publish(type));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['389']++;handle=ce._on(fn,context,arguments.length>3?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['142'][0]++,nativeSlice.call(arguments,3)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['142'][1]++,null),after?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['143'][0]++,'after'):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['143'][1]++,true));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['390']++;if(type.indexOf('*:')!==-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['144'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['391']++;this._hasSiblings=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['144'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['140'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['392']++;if(detachcategory){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['145'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['393']++;store[detachcategory]=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['146'][0]++,store[detachcategory])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['146'][1]++,{});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['394']++;store[detachcategory][type]=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['147'][0]++,store[detachcategory][type])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['147'][1]++,[]);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['395']++;store[detachcategory][type].push(handle);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['145'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['396']++;return yuievt.chain?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['148'][0]++,this):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['148'][1]++,handle);},subscribe:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['59']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['397']++;return this.on.apply(this,arguments);},detach:function(type,fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['60']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['398']++;var evts=this._yuievt.events,i,Node=Y.Node,isNode=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['149'][0]++,Node)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['149'][1]++,Y.instanceOf(this,Node));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['399']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['151'][0]++,!type)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['151'][1]++,this!==Y)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['150'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['400']++;for(i in evts){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['401']++;if(evts.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['152'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['402']++;evts[i].detach(fn,context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['152'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['403']++;if(isNode){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['153'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['404']++;Y.Event.purgeElement(Node.getDOMNode(this));}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['153'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['405']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['150'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['406']++;var parts=_parseType(type,this._yuievt.config.prefix),detachcategory=L.isArray(parts)?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['154'][0]++,parts[0]):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['154'][1]++,null),shorttype=parts?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['155'][0]++,parts[3]):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['155'][1]++,null),adapt,store=Y.Env.evt.handles,detachhost,cat,args,ce,keyDetacher=function(lcat,ltype,host){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['61']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['407']++;var handles=lcat[ltype],ce,i;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['408']++;if(handles){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['156'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['409']++;for(i=handles.length-1;i>=0;--i){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['410']++;ce=handles[i].evt;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['411']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['158'][0]++,ce.host===host)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['158'][1]++,ce.el===host)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['157'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['412']++;handles[i].detach();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['157'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['156'][1]++;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['413']++;if(detachcategory){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['159'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['414']++;cat=store[detachcategory];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['415']++;type=parts[1];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['416']++;detachhost=isNode?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['160'][0]++,Y.Node.getDOMNode(this)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['160'][1]++,this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['417']++;if(cat){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['161'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['418']++;if(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['162'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['419']++;keyDetacher(cat,type,detachhost);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['162'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['420']++;for(i in cat){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['421']++;if(cat.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['163'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['422']++;keyDetacher(cat,i,detachhost);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['163'][1]++;}}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['423']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['161'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['159'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['424']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['165'][0]++,L.isObject(type))&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['165'][1]++,type.detach)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['164'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['425']++;type.detach();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['426']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['164'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['427']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['167'][0]++,isNode)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['167'][1]++,!shorttype)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['167'][2]++,shorttype in Node.DOM_EVENTS))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['166'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['428']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['429']++;args[2]=Node.getDOMNode(this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['430']++;Y.detach.apply(Y,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['431']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['166'][1]++;}}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['432']++;adapt=Y.Env.evt.plugins[shorttype];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['433']++;if(Y.instanceOf(this,YUI)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['168'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['434']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['435']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['170'][0]++,adapt)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['170'][1]++,adapt.detach)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['169'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['436']++;adapt.detach.apply(Y,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['437']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['169'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['438']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][0]++,!type)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][1]++,!adapt)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][2]++,Node)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][3]++,type in Node.DOM_EVENTS)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['171'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['439']++;args[0]=type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['440']++;Y.Event.detach.apply(Y.Event,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['441']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['171'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['168'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['442']++;ce=evts[parts[1]];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['443']++;if(ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['173'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['444']++;ce.detach(fn,context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['173'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['445']++;return this;},unsubscribe:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['62']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['446']++;return this.detach.apply(this,arguments);},detachAll:function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['63']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['447']++;return this.detach(type);},unsubscribeAll:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['64']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['448']++;return this.detachAll.apply(this,arguments);},publish:function(type,opts){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['65']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['449']++;var ret,etState=this._yuievt,etConfig=etState.config,pre=etConfig.prefix;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['450']++;if(typeof type==='string'){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['174'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['451']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['175'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['452']++;type=_getType(type,pre);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['175'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['453']++;ret=this._publish(type,etConfig,opts);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['174'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['454']++;ret={};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['455']++;Y.each(type,function(v,k){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['66']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['456']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['176'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['457']++;k=_getType(k,pre);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['176'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['458']++;ret[k]=this._publish(k,etConfig,(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['177'][0]++,v)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['177'][1]++,opts));},this);}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['459']++;return ret;},_getFullType:function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['67']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['460']++;var pre=this._yuievt.config.prefix;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['461']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['178'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['462']++;return pre+PREFIX_DELIMITER+type;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['178'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['463']++;return type;}},_publish:function(fullType,etOpts,ceOpts){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['68']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['464']++;var ce,etState=this._yuievt,etConfig=etState.config,host=etConfig.host,context=etConfig.context,events=etState.events;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['465']++;ce=events[fullType];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['466']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][0]++,etConfig.monitored)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][1]++,!ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][2]++,ce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][3]++,ce.monitored)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['179'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['467']++;this._monitor('publish',fullType,{args:arguments});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['179'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['468']++;if(!ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['181'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['469']++;ce=events[fullType]=new Y.CustomEvent(fullType,etOpts);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['470']++;if(!etOpts){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['182'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['471']++;ce.host=host;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['472']++;ce.context=context;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['182'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['181'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['473']++;if(ceOpts){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['183'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['474']++;mixConfigs(ce,ceOpts,true);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['183'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['475']++;return ce;},_monitor:function(what,eventType,o){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['69']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['476']++;var monitorevt,ce,type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['477']++;if(eventType){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['184'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['478']++;if(typeof eventType==='string'){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['185'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['479']++;type=eventType;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['480']++;ce=this.getEvent(eventType,true);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['185'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['481']++;ce=eventType;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['482']++;type=eventType.type;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['483']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][0]++,this._yuievt.config.monitored)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][1]++,!ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][2]++,ce.monitored))||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][3]++,ce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][4]++,ce.monitored)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['186'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['484']++;monitorevt=type+'_'+what;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['485']++;o.monitored=what;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['486']++;this.fire.call(this,monitorevt,o);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['186'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['184'][1]++;}},fire:function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['70']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['487']++;var typeIncluded=typeof type==='string',argCount=arguments.length,t=type,yuievt=this._yuievt,etConfig=yuievt.config,pre=etConfig.prefix,ret,ce,ce2,args;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['488']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['189'][0]++,typeIncluded)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['189'][1]++,argCount<=3)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['188'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['489']++;if(argCount===2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['190'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['490']++;args=[arguments[1]];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['190'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['491']++;if(argCount===3){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['191'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['492']++;args=[arguments[1],arguments[2]];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['191'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['493']++;args=[];}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['188'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['494']++;args=nativeSlice.call(arguments,typeIncluded?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['192'][0]++,1):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['192'][1]++,0));}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['495']++;if(!typeIncluded){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['193'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['496']++;t=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['194'][0]++,type)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['194'][1]++,type.type);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['193'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['497']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['195'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['498']++;t=_getType(t,pre);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['195'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['499']++;ce=yuievt.events[t];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['500']++;if(this._hasSiblings){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['196'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['501']++;ce2=this.getSibling(t,ce);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['502']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['198'][0]++,ce2)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['198'][1]++,!ce)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['197'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['503']++;ce=this.publish(t);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['197'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['196'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['504']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['200'][0]++,etConfig.monitored)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['200'][1]++,!ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['200'][2]++,ce.monitored))||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['200'][3]++,ce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['200'][4]++,ce.monitored)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['199'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['505']++;this._monitor('fire',(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['201'][0]++,ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['201'][1]++,t),{args:args});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['199'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['506']++;if(!ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['202'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['507']++;if(yuievt.hasTargets){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['203'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['508']++;return this.bubble({type:t},args,this);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['203'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['509']++;ret=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['202'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['510']++;if(ce2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['204'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['511']++;ce.sibling=ce2;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['204'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['512']++;ret=ce._fire(args);}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['513']++;return yuievt.chain?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['205'][0]++,this):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['205'][1]++,ret);},getSibling:function(type,ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['71']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['514']++;var ce2;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['515']++;if(type.indexOf(PREFIX_DELIMITER)>-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['206'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['516']++;type=_wildType(type);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['517']++;ce2=this.getEvent(type,true);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['518']++;if(ce2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['207'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['519']++;ce2.applyConfig(ce);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['520']++;ce2.bubbles=false;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['521']++;ce2.broadcast=0;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['207'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['206'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['522']++;return ce2;},getEvent:function(type,prefixed){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['72']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['523']++;var pre,e;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['524']++;if(!prefixed){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['208'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['525']++;pre=this._yuievt.config.prefix;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['526']++;type=pre?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['209'][0]++,_getType(type,pre)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['209'][1]++,type);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['208'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['527']++;e=this._yuievt.events;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['528']++;return(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['210'][0]++,e[type])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['210'][1]++,null);},after:function(type,fn){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['73']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['529']++;var a=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['530']++;switch(L.type(type)){case'function':__cov_0ShtDtxkEapLmfzOgrY8Kw.b['211'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['531']++;return Y.Do.after.apply(Y.Do,arguments);case'array':__cov_0ShtDtxkEapLmfzOgrY8Kw.b['211'][1]++;case'object':__cov_0ShtDtxkEapLmfzOgrY8Kw.b['211'][2]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['532']++;a[0]._after=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['533']++;break;default:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['211'][3]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['534']++;a[0]=AFTER_PREFIX+type;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['535']++;return this.on.apply(this,a);},before:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['74']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['536']++;return this.on.apply(this,arguments);}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['537']++;Y.EventTarget=ET;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['538']++;Y.mix(Y,ET.prototype);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['539']++;ET.call(Y,{bubbles:false});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['540']++;YUI.Env.globalEvents=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['212'][0]++,YUI.Env.globalEvents)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['212'][1]++,new ET());__cov_0ShtDtxkEapLmfzOgrY8Kw.s['541']++;Y.Global=YUI.Env.globalEvents;},'@VERSION@',{'requires':['oop']});
website/src/pages/help/index.js
blitze/phpBB-ext-sitemaker
import React from 'react'; import Layout from '@theme/Layout'; import Link from '@docusaurus/Link'; import Translate from '@docusaurus/Translate'; import Hero from '../../components/Hero'; function Help() { return ( <Layout title="Help"> <Hero> <h2> <Translate>Need help?</Translate> </h2> <p> <Translate desc="statement made to reader"> This project is maintained by a dedicated group of people. </Translate> </p> </Hero> <div className="container margin-vert--xl"> <div className="row margin-top--lg"> <div className="col"> <h3> <Translate>Browse Docs</Translate> </h3> <p> <Translate values={{ documentation: ( <Link to="/docs/intro/introduction"> documentation </Link> ), }} > {'Learn more using the {documentation}'} </Translate> </p> </div> <div className="col"> <h3> <Translate>Join the community</Translate> </h3> <p> <Translate values={{support: <Link to="https://www.phpbb.com/customise/db/extension/phpbb_sitemaker_2/support">here</Link>}}> {'Ask questions about the documentation and project {support}'} </Translate> </p> </div> <div className="col"> <h3> <Translate>Stay up to date</Translate> </h3> <p> <Translate values={{blog: <Link to="/blog">blog</Link>}}> {"Find out what's new with this project on our {blog}"} </Translate> </p> </div> </div> </div> </Layout> ); } export default Help;
src/components/books/preview/BookPreviewFooter.js
great-design-and-systems/cataloguing-app
import { FontAwesome, ResponsiveButton } from '../../common/'; import { LABEL_ADD_BOOK, LABEL_CLOSE } from '../../../labels/'; import PropTypes from 'prop-types'; import React from 'react'; export const BookPreviewFooter = ({ closeDialog, addBook, readOnly }) => { return (<div className="btn-group btn-md"> {!readOnly && <ResponsiveButton onClick={addBook} className="btn btn-success" label={LABEL_ADD_BOOK} icon={ <FontAwesome name="plus" fixedWidth={true} size="lg" />} /> } <ResponsiveButton onClick={closeDialog} className="btn btn-danger" label={LABEL_CLOSE} icon={ <FontAwesome name="close" fixedWidth={true} size="lg" /> } /> </div>); }; BookPreviewFooter.propTypes = { readOnly: PropTypes.bool, addBook: PropTypes.func, closeDialog: PropTypes.func.isRequired };
src/interface/layout/Footer/index.js
FaideWW/WoWAnalyzer
import React from 'react'; import DiscordLogo from 'interface/icons/DiscordTiny'; import GithubLogo from 'interface/icons/GitHubMarkSmall'; import PatreonIcon from 'interface/icons/PatreonTiny'; import './style.css'; class Footer extends React.PureComponent { render() { return ( <footer> <div className="container text-center"> <a href="/"> <img src="/favicon.png" alt="Logo" className="wowanalyzer-logo" /> </a> <h1> Be a part of us </h1> <div className="social-links"> <a href="https://wowanalyzer.com/discord" data-tip="Discord"> <DiscordLogo /> </a> <a href="https://github.com/WoWAnalyzer/WoWAnalyzer" data-tip="GitHub"> <GithubLogo /> </a> <a href="https://www.patreon.com/wowanalyzer" data-tip="Patreon"> <PatreonIcon /> </a> </div><br /> <div style={{ opacity: 0.5, fontSize: '0.8em', fontWeight: 400, marginTop: '1em', }} > Log data from <a href="https://www.warcraftlogs.com">Warcaft Logs</a>. <dfn data-tip={` <ul> <li>Fingerprint by IconsGhost</li> <li>Scroll by jngll</li> <li>Delete by johartcamp</li> <li>Skull by Royyan Razka</li> <li>Heart by Emir Palavan</li> <li>armor by Jetro Cabau Quirós</li> <li>Checklist by David</li> <li>Idea by Anne</li> <li>About Document by Deepz</li> <li>Stats by Barracuda</li> <li>Dropdown by zalhan</li> </ul> `} >Icons by the <a href="https://thenounproject.com">Noun Project</a>.</dfn><br /> World of Warcraft and related artwork is copyright of Blizzard Entertainment, Inc.<br /> This is a fan site and we are not affiliated. </div> </div> </footer> ); } } export default Footer;
src/svg-icons/av/call-to-action.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvCallToAction = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3v-3h18v3z"/> </SvgIcon> ); AvCallToAction = pure(AvCallToAction); AvCallToAction.displayName = 'AvCallToAction'; export default AvCallToAction;
src/modules/background/components/FullscreenImage/index.js
emadalam/mesmerized
import React, { Component } from 'react'; import Image from '@components/Image'; import './style.css'; export const IMAGE_TYPE = { main: 'main', placeholder: 'placeholder' }; class FullScreenImage extends Component { state = { isLoading: true, }; handlePhotoLoad = (type = IMAGE_TYPE.main) => { const { onPhotoLoad } = this.props; this.setState({ isLoading: false }); onPhotoLoad && onPhotoLoad({ type }); }; handleOnload = () => { this.handlePhotoLoad(IMAGE_TYPE.main); }; handleOnError = () => { this.handlePhotoLoad(IMAGE_TYPE.placeholder); }; render() { const { src, placeholder, timeout, credits, previousPhotoUrl, } = this.props; const { isLoading } = this.state; return ( <div className="background"> <div className="background__imageContainer"> {previousPhotoUrl && <img src={previousPhotoUrl} alt="" className="background__image" />} <Image key={src} extraClasses="background__image" src={src} placeholder={placeholder} onLoad={this.handleOnload} onError={this.handleOnError} timeout={timeout} /> <div className={`background__overlay ${isLoading ? 'background__overlay_loading' : ''}`} /> </div> {credits && <div className="background__credits"> {credits} </div> } </div> ); } } export default FullScreenImage;
src/svg-icons/action/spellcheck.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSpellcheck = (props) => ( <SvgIcon {...props}> <path d="M12.45 16h2.09L9.43 3H7.57L2.46 16h2.09l1.12-3h5.64l1.14 3zm-6.02-5L8.5 5.48 10.57 11H6.43zm15.16.59l-8.09 8.09L9.83 16l-1.41 1.41 5.09 5.09L23 13l-1.41-1.41z"/> </SvgIcon> ); ActionSpellcheck = pure(ActionSpellcheck); ActionSpellcheck.displayName = 'ActionSpellcheck'; ActionSpellcheck.muiName = 'SvgIcon'; export default ActionSpellcheck;
src/AddTodo.js
lishengzxc/ReactReduxTodo
import React from 'react'; import ReactDOM from 'react-dom'; export default class AddTodo extends React.Component { render() { return ( <div> <input type='text' ref='input'/> <button onClick={e => this.handleClick(e)}> Add </button> </div> ); } handleClick(e) { const node = ReactDOM.findDOMNode(this.refs.input); const text = node.value.trim(); this.props.onAddClick(text); node.value = ''; } }
examples/src/components/States.js
paulmillr/react-select
import React from 'react'; import Select from 'react-select'; const STATES = require('../data/states'); var StatesField = React.createClass({ displayName: 'StatesField', propTypes: { label: React.PropTypes.string, searchable: React.PropTypes.bool, }, getDefaultProps () { return { label: 'States:', searchable: true, }; }, getInitialState () { return { country: 'AU', disabled: false, searchable: this.props.searchable, selectValue: 'new-south-wales', clearable: true, }; }, switchCountry (e) { var newCountry = e.target.value; console.log('Country changed to ' + newCountry); this.setState({ country: newCountry, selectValue: null }); }, updateValue (newValue) { console.log('State changed to ' + newValue); this.setState({ selectValue: newValue }); }, focusStateSelect () { this.refs.stateSelect.focus(); }, toggleCheckbox (e) { let newState = {}; newState[e.target.name] = e.target.checked; this.setState(newState); }, render () { var options = STATES[this.state.country]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select ref="stateSelect" autofocus options={options} simpleValue clearable={this.state.clearable} name="selected-state" disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} /> <div style={{ marginTop: 14 }}> <button type="button" onClick={this.focusStateSelect}>Focus Select</button> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Searchable</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Disabled</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="clearable" checked={this.state.clearable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Clearable</span> </label> </div> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/> <span className="checkbox-label">Australia</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/> <span className="checkbox-label">United States</span> </label> </div> </div> ); } }); module.exports = StatesField;
src/components/Feedback/Feedback.js
Zubergoff/project
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import s from './Feedback.scss'; import withStyles from '../../decorators/withStyles'; @withStyles(s) class Feedback extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <a className={s.link} href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className={s.spacer}>|</span> <a className={s.link} href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
ajax/libs/material-ui/4.9.4/es/FormControl/FormControlContext.js
cdnjs/cdnjs
import React from 'react'; /** * @ignore - internal component. */ const FormControlContext = React.createContext(); if (process.env.NODE_ENV !== 'production') { FormControlContext.displayName = 'FormControlContext'; } export function useFormControl() { return React.useContext(FormControlContext); } export default FormControlContext;
app/containers/Hero/HeroContainer.js
saelili/F3C_Website
import React from 'react' import { Hero } from '../../components' const HeroContainer = () => ( <Hero /> ) export default HeroContainer
test/PaginationSpec.js
xsistens/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, '»'); }); it('Should enumerate pagenums correctly when ellipsis=true', function () { const instance = ReactTestUtils.renderIntoDocument( <Pagination first last prev next ellipsis maxButtons={5} activePage={1} items={1} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(React.findDOMNode(pageButtons[0]).innerText, '«'); assert.equal(React.findDOMNode(pageButtons[1]).innerText, '‹'); assert.equal(React.findDOMNode(pageButtons[2]).innerText, '1'); assert.equal(React.findDOMNode(pageButtons[3]).innerText, '›'); assert.equal(React.findDOMNode(pageButtons[4]).innerText, '»'); }); it('Should render next and last buttons as disabled when items=0 and ellipsis=true', function () { const instance = ReactTestUtils.renderIntoDocument( <Pagination last next ellipsis maxButtons={1} activePage={1} items={0} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(React.findDOMNode(pageButtons[0]).innerText, '›'); assert.equal(React.findDOMNode(pageButtons[1]).innerText, '»'); assert.include(React.findDOMNode(pageButtons[0]).className, 'disabled'); assert.include(React.findDOMNode(pageButtons[1]).className, 'disabled'); }); it('Should wrap buttons in SafeAnchor when no buttonComponentClass prop is supplied', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination maxButtons={2} activePage={1} items={2} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); let tagName = 'A'; assert.equal(React.findDOMNode(pageButtons[0]).children[0].tagName, tagName); assert.equal(React.findDOMNode(pageButtons[1]).children[0].tagName, tagName); assert.equal(React.findDOMNode(pageButtons[0]).children[0].getAttribute('href'), ''); assert.equal(React.findDOMNode(pageButtons[1]).children[0].getAttribute('href'), ''); }); it('Should wrap each button in a buttonComponentClass when it is present', function () { class DummyElement extends React.Component { render() { return <div {...this.props}/>; } } let instance = ReactTestUtils.renderIntoDocument( <Pagination maxButtons={2} activePage={1} items={2} buttonComponentClass={DummyElement} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); let tagName = 'DIV'; assert.equal(React.findDOMNode(pageButtons[0]).children[0].tagName, tagName); assert.equal(React.findDOMNode(pageButtons[1]).children[0].tagName, tagName); }); it('Should call onSelect with custom buttonComponentClass', function (done) { class DummyElement extends React.Component { render() { return <div {...this.props}/>; } } function onSelect(event, selectedEvent) { assert.equal(selectedEvent.eventKey, 3); done(); } let 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 () { 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(React.findDOMNode(liElements[0]).className, 'disabled'); assert.include(React.findDOMNode(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 ); }); });
src/App.js
iamtonybologna/freebird
import React, { Component } from 'react'; import cookie from 'react-cookie'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import {fade} from 'material-ui/utils/colorManipulator'; import { cyan500, cyan700, deepPurple500, deepPurple50, deepPurple100, deepPurple900, pinkA200, lightGreenA400, grey100, grey300, grey400, grey500, white, darkBlack, fullBlack, fullWhite, } from 'material-ui/styles/colors'; import VideoEmbed from './VideoEmbed.js'; import HostVoteList from './HostVoteList.js'; import Splash from './splash.js'; import Loading from './Loading.js'; import Spaceman from './Spaceman.js'; import FloatingActionButton from 'material-ui/FloatingActionButton'; import Skip from 'material-ui/svg-icons/av/skip-next'; import Snackbar from 'material-ui/Snackbar'; import Three from './Three'; const muiTheme = getMuiTheme({ fontFamily: 'Roboto, sans-serif', palette: { primary1Color: deepPurple500, primary2Color: pinkA200, primary3Color: lightGreenA400, accent1Color: '#0ff', accent2Color: deepPurple500, accent3Color: deepPurple500, textColor: fullWhite, alternateTextColor: deepPurple900, canvasColor: '#303030', borderColor: deepPurple900, disabledColor: deepPurple100, pickerHeaderColor: deepPurple500, clockCircleColor: fade(deepPurple500, 0.07), shadowColor: deepPurple500, }, }); const styles = { newWinner: { position: 'absolute' }, } class App extends Component { constructor(props) { super(props); this.state = { votes: null, view: 'splash', upNext: [{ songId: 'JFDj3shXvco' }], winner: '', winnerName: '', displayVotes: [], open: false, playList: [], room: null }; this.renderView = () => { switch(this.state.view) { case 'splash': return ( <div> <Splash switcher={this.switcher} /> </div> ) case 'loading': return ( <div> <Three /> <Loading switcher={this.switcher} playList={this.state.playList} /> </div> ) case 'main': return ( <div> <Snackbar open={this.state.open} message={this.state.userCount + " users connected"} autoHideDuration={3000} onRequestClose={this.handleRequestClose} /> <VideoEmbed winner={this.setWinner} playList={this.state.playList} upNext={this.state.upNext} getUpNext={this.getUpNext} votes={this.state.votes} startParty={this.startParty} /> <HostVoteList votes={this.state.votes} upNext={this.state.upNext} winnerName={this.state.winnerName} /> </div> ) default: break; } }; }; switcher = (newView) => { this.setState({ view: newView }); }; handleRequestClose = () => { this.setState({ open: false, message: '' }); }; componentDidMount() { console.log('componentDidMount <App />'); if (cookie.load('room')) { console.log('cookie exists, joining room', cookie.load('room')); let roomId = cookie.load('room'); this.joinRoom(roomId); } else { console.log('no cookie found, creating room'); this.createRoom(); }; this.props.ws.on('updateUserCount', (data) => { console.log('Received a message from the server!', data); this.setState({ userCount: data.userCount, open: true }); }); this.props.ws.on('updateUpNext', (upNext) => { console.log('updateUpNext', upNext); this.setState({ upNext: upNext.data }); this.setState({ votes: null }); console.log('upNext', this.state.upNext); }); this.props.ws.on('votes', (data) => { console.log('votes', data); let displayVotes = data.votes; let oldUpNext = this.state.upNext; let p = []; for (let item in displayVotes) { if (item) { p.push(displayVotes[item]); } } if (p.length > 2) { for (let i = 0; i <= 2; i++) { oldUpNext[i].votes = p[i].length; } } this.setState({ votes: data.votes, upNext: oldUpNext }); console.log(this.state.upNext); }); this.props.ws.on('updatePlaylist', (playlist) => { console.log('updateplaylist', playlist.data); this.setState({playList: playlist.data}) }); this.props.ws.on('sendName', (data) => { console.log('name', data.name); }); this.props.ws.on('partyButton', (data) => { console.log('partyButtonCount', data.partyButtonCount, 'partyButtonCountLimit', data.partyButtonCountLimit); }); this.props.ws.on('sendNewSong', (data) => { console.log('song', data.song, 'name', data.song.uploaderName); }); }; componentWillUnmount() { console.log('Closing socket connection'); this.props.ws.close(); }; getUpNext = () => { this.props.ws.emit('getUpNext'); }; createRoom = () => { this.props.ws.emit('create', (roomId) => { this.setState({ room: roomId }); cookie.save('room', this.state.room); console.log('joined room', roomId); }); }; joinRoom = (roomId) => { this.props.ws.emit('join', { id: roomId }, (roomId) => { this.setState({ room: roomId }); console.log('joined room', roomId); }); }; setWinner = (newWinner) => { if (!newWinner) { this.setState({ winnerName: "" }); return } this.setState({ winner: newWinner }); let upNext = this.state.upNext; upNext.forEach((song) => { if (song.songId === newWinner) { this.setState({ winnerName: song.songTitle }); }; }); this.props.ws.emit('newWinner', { songId: this.state.winner }); }; startParty = () => { console.log('party\'s just getting started'); this.props.ws.emit('startParty'); }; render() { return ( <MuiThemeProvider muiTheme={muiTheme}> <div > { this.renderView() } </div> </MuiThemeProvider> ) }; }; export default App;
frontend/src/Settings/ImportLists/ImportLists/AddImportListItem.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Button from 'Components/Link/Button'; import Link from 'Components/Link/Link'; import Menu from 'Components/Menu/Menu'; import MenuContent from 'Components/Menu/MenuContent'; import { sizes } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import AddImportListPresetMenuItem from './AddImportListPresetMenuItem'; import styles from './AddImportListItem.css'; class AddImportListItem extends Component { // // Listeners onImportListSelect = () => { const { implementation } = this.props; this.props.onImportListSelect({ implementation }); } // // Render render() { const { implementation, implementationName, infoLink, presets, onImportListSelect } = this.props; const hasPresets = !!presets && !!presets.length; return ( <div className={styles.importList} > <Link className={styles.underlay} onPress={this.onImportListSelect} /> <div className={styles.overlay}> <div className={styles.name}> {implementationName} </div> <div className={styles.actions}> { hasPresets && <span> <Button size={sizes.SMALL} onPress={this.onImportListSelect} > {translate('Custom')} </Button> <Menu className={styles.presetsMenu}> <Button className={styles.presetsMenuButton} size={sizes.SMALL} > {translate('Presets')} </Button> <MenuContent> { presets.map((preset) => { return ( <AddImportListPresetMenuItem key={preset.name} name={preset.name} implementation={implementation} onPress={onImportListSelect} /> ); }) } </MenuContent> </Menu> </span> } <Button to={infoLink} size={sizes.SMALL} > {translate('MoreInfo')} </Button> </div> </div> </div> ); } } AddImportListItem.propTypes = { implementation: PropTypes.string.isRequired, implementationName: PropTypes.string.isRequired, infoLink: PropTypes.string.isRequired, presets: PropTypes.arrayOf(PropTypes.object), onImportListSelect: PropTypes.func.isRequired }; export default AddImportListItem;
core/router.js
a76/eric
import React from 'react' function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i++) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map(key => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET const url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Replace query parameters with actual values coming from `params` return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={route} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={route} params={params} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve }
test/daypickerinput/rendering.js
saenglert/react-day-picker
import React from 'react'; import ReactDOM from 'react-dom'; import { shallow, mount } from 'enzyme'; import DayPickerInput from '../../src/DayPickerInput'; import DayPicker from '../../src/DayPicker'; describe('DayPickerInput', () => { describe('rendering', () => { it('should have default props', () => { const dayPicker = <DayPickerInput />; expect(dayPicker.props.dayPickerProps).toEqual({}); expect(dayPicker.props.value).toBe(''); expect(dayPicker.props.format).toBe('L'); expect(dayPicker.props.hideOnDayClick).toBe(true); expect(dayPicker.props.component).toBe('input'); }); it('should have the right CSS classes', () => { const wrapper = shallow(<DayPickerInput />); expect(wrapper).toHaveClassName('DayPickerInput'); }); it('should set the month based on the specified format', () => { const wrapper = shallow( <DayPickerInput value="12/05/2010" format="DD/MM/YYYY" /> ); expect(wrapper.instance().state.month.getMonth()).toBe(4); expect(wrapper.instance().state.month.getFullYear()).toBe(2010); }); it('should not set the month if the value is not valid acording to `format`', () => { const wrapper = shallow( <DayPickerInput value="12/17/2010" format="DD/MM/YYYY" /> ); expect(wrapper.instance().state.month).toBeUndefined(); }); it('should accept multiple `format`s', () => { const wrapper = shallow( <DayPickerInput value="2010/05/12" format={['DD/MM/YYYY', 'YYYY/MM/DD']} /> ); expect(wrapper.instance().state.month.getMonth()).toBe(4); expect(wrapper.instance().state.month.getFullYear()).toBe(2010); }); it('should render an input field with the passed attributes', () => { const wrapper = shallow( <DayPickerInput value="12/14/2017" placeholder="bar" /> ); const input = wrapper.find('input'); expect(input).toBeDefined(); expect(input).toHaveProp('value', '12/14/2017'); expect(input).toHaveProp('placeholder', 'bar'); }); it('should work with not value dates', () => { const wrapper = shallow( <DayPickerInput value="very wrong" placeholder="bar" /> ); const input = wrapper.find('input'); expect(input).toHaveProp('value', 'very wrong'); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find(DayPicker)).toBeDefined(); }); it('should show the DayPicker', () => { const wrapper = shallow(<DayPickerInput />); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find('.DayPickerInput-OverlayWrapper')).toBeDefined(); expect(wrapper.find('.DayPickerInput-Overlay')).toBeDefined(); expect(wrapper.find(DayPicker)).toBeDefined(); }); it('should work with custom class names', () => { const wrapper = shallow( <DayPickerInput classNames={{ container: 'foo-container', overlayWrapper: 'foo-overlay-wrapper', overlay: 'foo-overlay', }} /> ); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find('.foo-container')).toBeDefined(); expect(wrapper.find('.foo-overlay-wrapper')).toBeDefined(); expect(wrapper.find('.foo-overlay')).toBeDefined(); }); it('should hide the DayPicker', () => { const wrapper = shallow(<DayPickerInput />); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find(DayPicker)).toHaveLength(1); wrapper.update(); wrapper.instance().hideDayPicker(); expect(wrapper.find('.DayPicker')).toHaveLength(0); }); it('should pass props to the DayPicker', () => { const instance = mount( <DayPickerInput dayPickerProps={{ enableOutsideDays: true, numberOfMonths: 12, fixedWeeks: false, }} /> ).instance(); instance.showDayPicker(); expect(instance.daypicker.props.fixedWeeks).toBe(false); expect(instance.daypicker.props.enableOutsideDays).toBe(true); expect(instance.daypicker.props.numberOfMonths).toBe(12); }); it('should open the daypicker to the month of the selected day', () => { const wrapper = mount(<DayPickerInput value="12/15/2017" />); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find('.DayPicker-Caption div').first()).toHaveText( 'December 2017' ); }); it('should display the current value as a selected day', () => { const wrapper = mount(<DayPickerInput value="12/15/2017" />); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find('.DayPicker-Day--selected')).toHaveLength(1); expect(wrapper.find('.DayPicker-Day--selected')).toHaveText('15'); }); it('should update the current value when `value` prop is updated', () => { const wrapper = mount(<DayPickerInput value="12/15/2017" />); wrapper.setProps({ value: '01/10/2018' }); expect(wrapper.instance().state.value).toBe('01/10/2018'); }); it('should not update the current value when other props are updated', () => { const wrapper = mount(<DayPickerInput value="12/15/2017" />); wrapper.setProps({ dayPickerProps: {} }); expect(wrapper.instance().state.value).toBe('12/15/2017'); }); it("should update the displayed month when `dayPickerProps.month`'s month is updated", () => { const wrapper = mount(<DayPickerInput value="12/15/2017" />); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find('.DayPicker-Caption').first()).toHaveText( 'December 2017' ); wrapper.setProps({ dayPickerProps: { month: new Date(2017, 10) } }); expect(wrapper.instance().state.value).toBe('12/15/2017'); expect(wrapper.find('.DayPicker-Caption').first()).toHaveText( 'November 2017' ); }); it("should update the displayed month when `dayPickerProps.month`'s year is updated", () => { const wrapper = mount(<DayPickerInput value="12/15/2017" />); wrapper.instance().showDayPicker(); wrapper.update(); expect(wrapper.find('.DayPicker-Caption').first()).toHaveText( 'December 2017' ); wrapper.setProps({ dayPickerProps: { month: new Date(2016, 10) } }); expect(wrapper.instance().state.value).toBe('12/15/2017'); expect(wrapper.find('.DayPicker-Caption').first()).toHaveText( 'November 2016' ); }); it('should not update the current value when other props are updated', () => { const wrapper = mount(<DayPickerInput value="12/15/2017" />); wrapper.setProps({ dayPickerProps: {} }); expect(wrapper.instance().state.value).toBe('12/15/2017'); }); it('should clear timeouts when component unmounts', () => { const container = document.createElement('div'); mount(<DayPickerInput />, { attachTo: container }); const spy = jest.spyOn(window, 'clearTimeout'); ReactDOM.unmountComponentAtNode(container); expect(spy).toHaveBeenCalledTimes(2); spy.mockRestore(); }); }); });
packages/react-dom/src/server/ReactPartialRenderer.js
krasimir/react
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactElement} from 'shared/ReactElementType'; import type { ReactProvider, ReactConsumer, ReactContext, } from 'shared/ReactTypes'; import React from 'react'; import invariant from 'shared/invariant'; import getComponentName from 'shared/getComponentName'; import lowPriorityWarning from 'shared/lowPriorityWarning'; import warning from 'shared/warning'; import checkPropTypes from 'prop-types/checkPropTypes'; import describeComponentFrame from 'shared/describeComponentFrame'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import {warnAboutDeprecatedLifecycles} from 'shared/ReactFeatureFlags'; import { REACT_FORWARD_REF_TYPE, REACT_FRAGMENT_TYPE, REACT_STRICT_MODE_TYPE, REACT_ASYNC_MODE_TYPE, REACT_PORTAL_TYPE, REACT_PROFILER_TYPE, REACT_PROVIDER_TYPE, REACT_CONTEXT_TYPE, } from 'shared/ReactSymbols'; import { createMarkupForCustomAttribute, createMarkupForProperty, createMarkupForRoot, } from './DOMMarkupOperations'; import escapeTextForBrowser from './escapeTextForBrowser'; import { Namespaces, getIntrinsicNamespace, getChildNamespace, } from '../shared/DOMNamespaces'; import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes'; import assertValidProps from '../shared/assertValidProps'; import dangerousStyleValue from '../shared/dangerousStyleValue'; import hyphenateStyleName from '../shared/hyphenateStyleName'; import isCustomComponent from '../shared/isCustomComponent'; import omittedCloseTags from '../shared/omittedCloseTags'; import warnValidStyle from '../shared/warnValidStyle'; import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook'; import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook'; import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook'; // Based on reading the React.Children implementation. TODO: type this somewhere? type ReactNode = string | number | ReactElement; type FlatReactChildren = Array<null | ReactNode>; type toArrayType = (children: mixed) => FlatReactChildren; const toArray = ((React.Children.toArray: any): toArrayType); // This is only used in DEV. // Each entry is `this.stack` from a currently executing renderer instance. // (There may be more than one because ReactDOMServer is reentrant). // Each stack is an array of frames which may contain nested stacks of elements. let currentDebugStacks = []; let ReactDebugCurrentFrame; let prevGetCurrentStackImpl = null; let getCurrentServerStackImpl = () => ''; let describeStackFrame = element => ''; let validatePropertiesInDevelopment = (type, props) => {}; let pushCurrentDebugStack = (stack: Array<Frame>) => {}; let pushElementToDebugStack = (element: ReactElement) => {}; let popCurrentDebugStack = () => {}; if (__DEV__) { ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; validatePropertiesInDevelopment = function(type, props) { validateARIAProperties(type, props); validateInputProperties(type, props); validateUnknownProperties(type, props, /* canUseEventSystem */ false); }; describeStackFrame = function(element): string { const source = element._source; const type = element.type; const name = getComponentName(type); const ownerName = null; return describeComponentFrame(name, source, ownerName); }; pushCurrentDebugStack = function(stack: Array<Frame>) { currentDebugStacks.push(stack); if (currentDebugStacks.length === 1) { // We are entering a server renderer. // Remember the previous (e.g. client) global stack implementation. prevGetCurrentStackImpl = ReactDebugCurrentFrame.getCurrentStack; ReactDebugCurrentFrame.getCurrentStack = getCurrentServerStackImpl; } }; pushElementToDebugStack = function(element: ReactElement) { // For the innermost executing ReactDOMServer call, const stack = currentDebugStacks[currentDebugStacks.length - 1]; // Take the innermost executing frame (e.g. <Foo>), const frame: Frame = stack[stack.length - 1]; // and record that it has one more element associated with it. ((frame: any): FrameDev).debugElementStack.push(element); // We only need this because we tail-optimize single-element // children and directly handle them in an inner loop instead of // creating separate frames for them. }; popCurrentDebugStack = function() { currentDebugStacks.pop(); if (currentDebugStacks.length === 0) { // We are exiting the server renderer. // Restore the previous (e.g. client) global stack implementation. ReactDebugCurrentFrame.getCurrentStack = prevGetCurrentStackImpl; prevGetCurrentStackImpl = null; } }; getCurrentServerStackImpl = function(): string { if (currentDebugStacks.length === 0) { // Nothing is currently rendering. return ''; } // ReactDOMServer is reentrant so there may be multiple calls at the same time. // Take the frames from the innermost call which is the last in the array. let frames = currentDebugStacks[currentDebugStacks.length - 1]; let stack = ''; // Go through every frame in the stack from the innermost one. for (let i = frames.length - 1; i >= 0; i--) { const frame: Frame = frames[i]; // Every frame might have more than one debug element stack entry associated with it. // This is because single-child nesting doesn't create materialized frames. // Instead it would push them through `pushElementToDebugStack()`. let debugElementStack = ((frame: any): FrameDev).debugElementStack; for (let ii = debugElementStack.length - 1; ii >= 0; ii--) { stack += describeStackFrame(debugElementStack[ii]); } } return stack; }; } let didWarnDefaultInputValue = false; let didWarnDefaultChecked = false; let didWarnDefaultSelectValue = false; let didWarnDefaultTextareaValue = false; let didWarnInvalidOptionChildren = false; const didWarnAboutNoopUpdateForComponent = {}; const didWarnAboutBadClass = {}; const didWarnAboutDeprecatedWillMount = {}; const didWarnAboutUndefinedDerivedState = {}; const didWarnAboutUninitializedState = {}; const valuePropNames = ['value', 'defaultValue']; const newlineEatingTags = { listing: true, pre: true, textarea: true, }; // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name const VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset const validatedTagCache = {}; function validateDangerousTag(tag) { if (!validatedTagCache.hasOwnProperty(tag)) { invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag); validatedTagCache[tag] = true; } } const styleNameCache = {}; const processStyleName = function(styleName) { if (styleNameCache.hasOwnProperty(styleName)) { return styleNameCache[styleName]; } const result = hyphenateStyleName(styleName); styleNameCache[styleName] = result; return result; }; function createMarkupForStyles(styles): string | null { let serialized = ''; let delimiter = ''; for (const styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } const isCustomProperty = styleName.indexOf('--') === 0; const styleValue = styles[styleName]; if (__DEV__) { if (!isCustomProperty) { warnValidStyle(styleName, styleValue, getCurrentServerStackImpl); } } if (styleValue != null) { serialized += delimiter + processStyleName(styleName) + ':'; serialized += dangerousStyleValue( styleName, styleValue, isCustomProperty, ); delimiter = ';'; } } return serialized || null; } function warnNoop( publicInstance: React$Component<any, any>, callerName: string, ) { if (__DEV__) { const constructor = publicInstance.constructor; const componentName = (constructor && getComponentName(constructor)) || 'ReactClass'; const warningKey = componentName + '.' + callerName; if (didWarnAboutNoopUpdateForComponent[warningKey]) { return; } warning( false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName, ); didWarnAboutNoopUpdateForComponent[warningKey] = true; } } function shouldConstruct(Component) { return Component.prototype && Component.prototype.isReactComponent; } function getNonChildrenInnerMarkup(props) { const innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return innerHTML.__html; } } else { const content = props.children; if (typeof content === 'string' || typeof content === 'number') { return escapeTextForBrowser(content); } } return null; } function flattenTopLevelChildren(children: mixed): FlatReactChildren { if (!React.isValidElement(children)) { return toArray(children); } const element = ((children: any): ReactElement); if (element.type !== REACT_FRAGMENT_TYPE) { return [element]; } const fragmentChildren = element.props.children; if (!React.isValidElement(fragmentChildren)) { return toArray(fragmentChildren); } const fragmentChildElement = ((fragmentChildren: any): ReactElement); return [fragmentChildElement]; } function flattenOptionChildren(children: mixed): ?string { if (children === undefined || children === null) { return children; } let content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function(child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { if (__DEV__) { if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; warning( false, 'Only strings and numbers are supported as <option> children.', ); } } } }); return content; } const emptyObject = {}; if (__DEV__) { Object.freeze(emptyObject); } function maskContext(type, context) { const contextTypes = type.contextTypes; if (!contextTypes) { return emptyObject; } const maskedContext = {}; for (const contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; } function checkContextTypes(typeSpecs, values, location: string) { if (__DEV__) { checkPropTypes( typeSpecs, values, location, 'Component', getCurrentServerStackImpl, ); } } function processContext(type, context) { const maskedContext = maskContext(type, context); if (__DEV__) { if (type.contextTypes) { checkContextTypes(type.contextTypes, maskedContext, 'context'); } } return maskedContext; } const STYLE = 'style'; const RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null, suppressHydrationWarning: null, }; function createOpenTagMarkup( tagVerbatim: string, tagLowercase: string, props: Object, namespace: string, makeStaticMarkup: boolean, isRootElement: boolean, ): string { let ret = '<' + tagVerbatim; for (const propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } let propValue = props[propKey]; if (propValue == null) { continue; } if (propKey === STYLE) { propValue = createMarkupForStyles(propValue); } let markup = null; if (isCustomComponent(tagLowercase, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = createMarkupForCustomAttribute(propKey, propValue); } } else { markup = createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (makeStaticMarkup) { return ret; } if (isRootElement) { ret += ' ' + createMarkupForRoot(); } return ret; } function validateRenderResult(child, type) { if (child === undefined) { invariant( false, '%s(...): Nothing was returned from render. This usually means a ' + 'return statement is missing. Or, to render nothing, ' + 'return null.', getComponentName(type) || 'Component', ); } } function resolve( child: mixed, context: Object, ): {| child: mixed, context: Object, |} { while (React.isValidElement(child)) { // Safe because we just checked it's an element. let element: ReactElement = (child: any); let Component = element.type; if (__DEV__) { pushElementToDebugStack(element); } if (typeof Component !== 'function') { break; } processChild(element, Component); } // Extra closure so queue and replace can be captured properly function processChild(element, Component) { let publicContext = processContext(Component, context); let queue = []; let replace = false; let updater = { isMounted: function(publicInstance) { return false; }, enqueueForceUpdate: function(publicInstance) { if (queue === null) { warnNoop(publicInstance, 'forceUpdate'); return null; } }, enqueueReplaceState: function(publicInstance, completeState) { replace = true; queue = [completeState]; }, enqueueSetState: function(publicInstance, currentPartialState) { if (queue === null) { warnNoop(publicInstance, 'setState'); return null; } queue.push(currentPartialState); }, }; let inst; if (shouldConstruct(Component)) { inst = new Component(element.props, publicContext, updater); if (typeof Component.getDerivedStateFromProps === 'function') { if (__DEV__) { if (inst.state === null || inst.state === undefined) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutUninitializedState[componentName]) { warning( false, '%s: Did not properly initialize state during construction. ' + 'Expected state to be an object, but it was %s.', componentName, inst.state === null ? 'null' : 'undefined', ); didWarnAboutUninitializedState[componentName] = true; } } } let partialState = Component.getDerivedStateFromProps.call( null, element.props, inst.state, ); if (__DEV__) { if (partialState === undefined) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutUndefinedDerivedState[componentName]) { warning( false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName, ); didWarnAboutUndefinedDerivedState[componentName] = true; } } } if (partialState != null) { inst.state = Object.assign({}, inst.state, partialState); } } } else { if (__DEV__) { if ( Component.prototype && typeof Component.prototype.render === 'function' ) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutBadClass[componentName]) { warning( false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName, ); didWarnAboutBadClass[componentName] = true; } } } inst = Component(element.props, publicContext, updater); if (inst == null || inst.render == null) { child = inst; validateRenderResult(child, Component); return; } } inst.props = element.props; inst.context = publicContext; inst.updater = updater; let initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } if ( typeof inst.UNSAFE_componentWillMount === 'function' || typeof inst.componentWillMount === 'function' ) { if (typeof inst.componentWillMount === 'function') { if (__DEV__) { if ( warnAboutDeprecatedLifecycles && inst.componentWillMount.__suppressDeprecationWarning !== true ) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutDeprecatedWillMount[componentName]) { lowPriorityWarning( false, '%s: componentWillMount() is deprecated and will be ' + 'removed in the next major version. Read about the motivations ' + 'behind this change: ' + 'https://fb.me/react-async-component-lifecycle-hooks' + '\n\n' + 'As a temporary workaround, you can rename to ' + 'UNSAFE_componentWillMount instead.', componentName, ); didWarnAboutDeprecatedWillMount[componentName] = true; } } } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for any component with the new gDSFP. if (typeof Component.getDerivedStateFromProps !== 'function') { inst.componentWillMount(); } } if ( typeof inst.UNSAFE_componentWillMount === 'function' && typeof Component.getDerivedStateFromProps !== 'function' ) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for any component with the new gDSFP. inst.UNSAFE_componentWillMount(); } if (queue.length) { let oldQueue = queue; let oldReplace = replace; queue = null; replace = false; if (oldReplace && oldQueue.length === 1) { inst.state = oldQueue[0]; } else { let nextState = oldReplace ? oldQueue[0] : inst.state; let dontMutate = true; for (let i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { let partial = oldQueue[i]; let partialState = typeof partial === 'function' ? partial.call(inst, nextState, element.props, publicContext) : partial; if (partialState != null) { if (dontMutate) { dontMutate = false; nextState = Object.assign({}, nextState, partialState); } else { Object.assign(nextState, partialState); } } } inst.state = nextState; } } else { queue = null; } } child = inst.render(); if (__DEV__) { if (child === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. child = null; } } validateRenderResult(child, Component); let childContext; if (typeof inst.getChildContext === 'function') { let childContextTypes = Component.childContextTypes; if (typeof childContextTypes === 'object') { childContext = inst.getChildContext(); for (let contextKey in childContext) { invariant( contextKey in childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(Component) || 'Unknown', contextKey, ); } } else { warning( false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', getComponentName(Component) || 'Unknown', ); } } if (childContext) { context = Object.assign({}, context, childContext); } } return {child, context}; } type Frame = { type: mixed, domNamespace: string, children: FlatReactChildren, childIndex: number, context: Object, footer: string, }; type FrameDev = Frame & { debugElementStack: Array<ReactElement>, }; class ReactDOMServerRenderer { stack: Array<Frame>; exhausted: boolean; // TODO: type this more strictly: currentSelectValue: any; previousWasTextNode: boolean; makeStaticMarkup: boolean; contextIndex: number; contextStack: Array<ReactContext<any>>; contextValueStack: Array<any>; contextProviderStack: ?Array<ReactProvider<any>>; // DEV-only constructor(children: mixed, makeStaticMarkup: boolean) { const flatChildren = flattenTopLevelChildren(children); const topFrame: Frame = { type: null, // Assume all trees start in the HTML namespace (not totally true, but // this is what we did historically) domNamespace: Namespaces.html, children: flatChildren, childIndex: 0, context: emptyObject, footer: '', }; if (__DEV__) { ((topFrame: any): FrameDev).debugElementStack = []; } this.stack = [topFrame]; this.exhausted = false; this.currentSelectValue = null; this.previousWasTextNode = false; this.makeStaticMarkup = makeStaticMarkup; // Context (new API) this.contextIndex = -1; this.contextStack = []; this.contextValueStack = []; if (__DEV__) { this.contextProviderStack = []; } } /** * Note: We use just two stacks regardless of how many context providers you have. * Providers are always popped in the reverse order to how they were pushed * so we always know on the way down which provider you'll encounter next on the way up. * On the way down, we push the current provider, and its context value *before* * we mutated it, onto the stacks. Therefore, on the way up, we always know which * provider needs to be "restored" to which value. * https://github.com/facebook/react/pull/12985#issuecomment-396301248 */ pushProvider<T>(provider: ReactProvider<T>): void { const index = ++this.contextIndex; const context: ReactContext<any> = provider.type._context; const previousValue = context._currentValue; // Remember which value to restore this context to on our way up. this.contextStack[index] = context; this.contextValueStack[index] = previousValue; if (__DEV__) { // Only used for push/pop mismatch warnings. (this.contextProviderStack: any)[index] = provider; } // Mutate the current value. context._currentValue = provider.props.value; } popProvider<T>(provider: ReactProvider<T>): void { const index = this.contextIndex; if (__DEV__) { warning( index > -1 && provider === (this.contextProviderStack: any)[index], 'Unexpected pop.', ); } const context: ReactContext<any> = this.contextStack[index]; const previousValue = this.contextValueStack[index]; // "Hide" these null assignments from Flow by using `any` // because conceptually they are deletions--as long as we // promise to never access values beyond `this.contextIndex`. this.contextStack[index] = (null: any); this.contextValueStack[index] = (null: any); if (__DEV__) { (this.contextProviderStack: any)[index] = (null: any); } this.contextIndex--; // Restore to the previous value we stored as we were walking down. context._currentValue = previousValue; } read(bytes: number): string | null { if (this.exhausted) { return null; } let out = ''; while (out.length < bytes) { if (this.stack.length === 0) { this.exhausted = true; break; } const frame: Frame = this.stack[this.stack.length - 1]; if (frame.childIndex >= frame.children.length) { const footer = frame.footer; out += footer; if (footer !== '') { this.previousWasTextNode = false; } this.stack.pop(); if (frame.type === 'select') { this.currentSelectValue = null; } else if ( frame.type != null && frame.type.type != null && frame.type.type.$$typeof === REACT_PROVIDER_TYPE ) { const provider: ReactProvider<any> = (frame.type: any); this.popProvider(provider); } continue; } const child = frame.children[frame.childIndex++]; if (__DEV__) { pushCurrentDebugStack(this.stack); // We're starting work on this frame, so reset its inner stack. ((frame: any): FrameDev).debugElementStack.length = 0; try { // Be careful! Make sure this matches the PROD path below. out += this.render(child, frame.context, frame.domNamespace); } finally { popCurrentDebugStack(); } } else { // Be careful! Make sure this matches the DEV path above. out += this.render(child, frame.context, frame.domNamespace); } } return out; } render( child: ReactNode | null, context: Object, parentNamespace: string, ): string { if (typeof child === 'string' || typeof child === 'number') { const text = '' + child; if (text === '') { return ''; } if (this.makeStaticMarkup) { return escapeTextForBrowser(text); } if (this.previousWasTextNode) { return '<!-- -->' + escapeTextForBrowser(text); } this.previousWasTextNode = true; return escapeTextForBrowser(text); } else { let nextChild; ({child: nextChild, context} = resolve(child, context)); if (nextChild === null || nextChild === false) { return ''; } else if (!React.isValidElement(nextChild)) { if (nextChild != null && nextChild.$$typeof != null) { // Catch unexpected special types early. const $$typeof = nextChild.$$typeof; invariant( $$typeof !== REACT_PORTAL_TYPE, 'Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.', ); // Catch-all to prevent an infinite loop if React.Children.toArray() supports some new type. invariant( false, 'Unknown element-like object type: %s. This is likely a bug in React. ' + 'Please file an issue.', ($$typeof: any).toString(), ); } const nextChildren = toArray(nextChild); const frame: Frame = { type: null, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); return ''; } // Safe because we just checked it's an element. const nextElement = ((nextChild: any): ReactElement); const elementType = nextElement.type; if (typeof elementType === 'string') { return this.renderDOM(nextElement, context, parentNamespace); } switch (elementType) { case REACT_STRICT_MODE_TYPE: case REACT_ASYNC_MODE_TYPE: case REACT_PROFILER_TYPE: case REACT_FRAGMENT_TYPE: { const nextChildren = toArray( ((nextChild: any): ReactElement).props.children, ); const frame: Frame = { type: null, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); return ''; } // eslint-disable-next-line-no-fallthrough default: break; } if (typeof elementType === 'object' && elementType !== null) { switch (elementType.$$typeof) { case REACT_FORWARD_REF_TYPE: { const element: ReactElement = ((nextChild: any): ReactElement); const nextChildren = toArray( elementType.render(element.props, element.ref), ); const frame: Frame = { type: null, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); return ''; } case REACT_PROVIDER_TYPE: { const provider: ReactProvider<any> = (nextChild: any); const nextProps = provider.props; const nextChildren = toArray(nextProps.children); const frame: Frame = { type: provider, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.pushProvider(provider); this.stack.push(frame); return ''; } case REACT_CONTEXT_TYPE: { const consumer: ReactConsumer<any> = (nextChild: any); const nextProps: any = consumer.props; const nextValue = consumer.type._currentValue; const nextChildren = toArray(nextProps.children(nextValue)); const frame: Frame = { type: nextChild, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); return ''; } default: break; } } let info = ''; if (__DEV__) { const owner = nextElement._owner; if ( elementType === undefined || (typeof elementType === 'object' && elementType !== null && Object.keys(elementType).length === 0) ) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; } const ownerName = owner ? getComponentName(owner) : null; if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } invariant( false, 'Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + 'but got: %s.%s', elementType == null ? elementType : typeof elementType, info, ); } } renderDOM( element: ReactElement, context: Object, parentNamespace: string, ): string { const tag = element.type.toLowerCase(); let namespace = parentNamespace; if (parentNamespace === Namespaces.html) { namespace = getIntrinsicNamespace(tag); } if (__DEV__) { if (namespace === Namespaces.html) { // Should this check be gated by parent namespace? Not sure we want to // allow <SVG> or <mATH>. warning( tag === element.type, '<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', element.type, ); } } validateDangerousTag(tag); let props = element.props; if (tag === 'input') { if (__DEV__) { ReactControlledValuePropTypes.checkPropTypes( 'input', props, getCurrentServerStackImpl, ); if ( props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked ) { warning( false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type, ); didWarnDefaultChecked = true; } if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue ) { warning( false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type, ); didWarnDefaultInputValue = true; } } props = Object.assign( { type: undefined, }, props, { defaultChecked: undefined, defaultValue: undefined, value: props.value != null ? props.value : props.defaultValue, checked: props.checked != null ? props.checked : props.defaultChecked, }, ); } else if (tag === 'textarea') { if (__DEV__) { ReactControlledValuePropTypes.checkPropTypes( 'textarea', props, getCurrentServerStackImpl, ); if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue ) { warning( false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', ); didWarnDefaultTextareaValue = true; } } let initialValue = props.value; if (initialValue == null) { let defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. let textareaChildren = props.children; if (textareaChildren != null) { if (__DEV__) { warning( false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.', ); } invariant( defaultValue == null, 'If you supply `defaultValue` on a <textarea>, do not pass children.', ); if (Array.isArray(textareaChildren)) { invariant( textareaChildren.length <= 1, '<textarea> can only have at most one child.', ); textareaChildren = textareaChildren[0]; } defaultValue = '' + textareaChildren; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } props = Object.assign({}, props, { value: undefined, children: '' + initialValue, }); } else if (tag === 'select') { if (__DEV__) { ReactControlledValuePropTypes.checkPropTypes( 'select', props, getCurrentServerStackImpl, ); for (let i = 0; i < valuePropNames.length; i++) { const propName = valuePropNames[i]; if (props[propName] == null) { continue; } const isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { warning( false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, '', // getDeclarationErrorAddendum(), ); } else if (!props.multiple && isArray) { warning( false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, '', // getDeclarationErrorAddendum(), ); } } if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue ) { warning( false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', ); didWarnDefaultSelectValue = true; } } this.currentSelectValue = props.value != null ? props.value : props.defaultValue; props = Object.assign({}, props, { value: undefined, }); } else if (tag === 'option') { let selected = null; const selectValue = this.currentSelectValue; const optionChildren = flattenOptionChildren(props.children); if (selectValue != null) { let value; if (props.value != null) { value = props.value + ''; } else { value = optionChildren; } selected = false; if (Array.isArray(selectValue)) { // multiple for (let j = 0; j < selectValue.length; j++) { if ('' + selectValue[j] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } props = Object.assign( { selected: undefined, children: undefined, }, props, { selected: selected, children: optionChildren, }, ); } } if (__DEV__) { validatePropertiesInDevelopment(tag, props); } assertValidProps(tag, props, getCurrentServerStackImpl); let out = createOpenTagMarkup( element.type, tag, props, namespace, this.makeStaticMarkup, this.stack.length === 1, ); let footer = ''; if (omittedCloseTags.hasOwnProperty(tag)) { out += '/>'; } else { out += '>'; footer = '</' + element.type + '>'; } let children; const innerMarkup = getNonChildrenInnerMarkup(props); if (innerMarkup != null) { children = []; if (newlineEatingTags[tag] && innerMarkup.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> out += '\n'; } out += innerMarkup; } else { children = toArray(props.children); } const frame = { domNamespace: getChildNamespace(parentNamespace, element.type), type: tag, children, childIndex: 0, context: context, footer: footer, }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); this.previousWasTextNode = false; return out; } } export default ReactDOMServerRenderer;
src/components/Pagination.js
MunGell/elemental
var React = require('react'); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'Pagination', propTypes: { className: React.PropTypes.string, currentPage: React.PropTypes.number.isRequired, onPageSelect: React.PropTypes.func, pageSize: React.PropTypes.number.isRequired, plural: React.PropTypes.string, singular: React.PropTypes.string, style: React.PropTypes.object, total: React.PropTypes.number.isRequired, limit: React.PropTypes.number }, renderCount () { let count = ''; let { currentPage, pageSize, plural, singular, total } = this.props; if (!total) { count = 'No ' + (plural || 'records'); } else if (total > pageSize) { let start = (pageSize * (currentPage - 1)) + 1; let end = Math.min(start + pageSize - 1, total); count = `Showing ${start} to ${end} of ${total}`; } else { count = 'Showing ' + total; if (total > 1 && plural) { count += ' ' + plural; } else if (total === 1 && singular) { count += ' ' + singular; } } return ( <div className="Pagination__count">{count}</div> ); }, onPageSelect (i) { if (!this.props.onPageSelect) return; this.props.onPageSelect(i); }, renderPages () { if (this.props.total <= this.props.pageSize) return null; let pages = []; let { currentPage, pageSize, total, limit } = this.props; let totalPages = Math.ceil(total / pageSize); let minPage = 0; let maxPage = totalPages; if (limit && (limit < totalPages)) { limit = Math.floor(limit / 2); minPage = currentPage - limit - 1; maxPage = currentPage + limit; if (minPage < 0) { maxPage = maxPage - minPage; minPage = 0; } if (maxPage > totalPages) { minPage = totalPages - 2 * limit - 1; maxPage = totalPages; } } if (minPage > 0) { pages.push(<button key={'page_start'} className={'Pagination__list__item'} onClick={() => this.onPageSelect(1)}>...</button>); } for (let i = minPage; i < maxPage; i++) { let page = i + 1; let current = (page === currentPage); let className = classNames('Pagination__list__item', { 'is-selected': current }); /* eslint-disable no-loop-func */ pages.push(<button key={'page_' + page} className={className} onClick={() => this.onPageSelect(page)}>{page}</button>); /* eslint-enable */ } if (maxPage < totalPages) { pages.push(<button key={'page_end'} className={'Pagination__list__item'} onClick={() => this.onPageSelect(totalPages)}>...</button>); } return ( <div className="Pagination__list"> {pages} </div> ); }, render () { var className = classNames('Pagination', this.props.className); return ( <div className={className} style={this.props.style}> {this.renderCount()} {this.renderPages()} </div> ); } });
packages/logos/src/percona.js
geek/joyent-portal
import React from 'react'; export default props => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 42 42" {...props}> <title>Artboard 1 copy 11</title> <path fill="#1B3240" d="M21.05 3.4c-9.9 0-18 7.9-18 17.5A17.69 17.69 0 0 0 11 35.5V20.7a10.2 10.2 0 0 1 10-10.2 10.18 10.18 0 0 1 10 10.4 10.25 10.25 0 0 1-10 10.4 9.6 9.6 0 0 1-5.8-1.9v8.2a18.53 18.53 0 0 0 5.8.9c9.9 0 18-7.9 18-17.5A17.76 17.76 0 0 0 21.05 3.4" /> <path fill="#1B3240" d="M27.15 21.2a6 6 0 1 1-6-6 6 6 0 0 1 6 6" /> </svg> );
src/pages/paper/edit/editForm.js
sunway-official/acm-admin
import React, { Component } from 'react'; import CustomInput from 'components/CustomInput'; import { renderSelectField } from 'components/render'; import { reduxForm, Field } from 'redux-form'; import validate from '../validate'; import { RaisedButton, Subheader, MenuItem } from 'material-ui'; import { Link } from 'react-router-dom'; import EditAuthors from './editAuthors'; import { FieldArray } from 'redux-form'; import FileInput from 'components/render/FileRender'; import { countryData } from '../countryData'; class EditPaperForm extends Component { constructor(props) { super(props); this.state = { checked: false, }; } updateCheck() { this.setState(oldState => { return { checked: !oldState.checked, }; }); } render() { const topics = this.props.topics; const { handleSubmit, pristine, handleUploadFile } = this.props; return ( <form className="form conference-info add-paper-form" onSubmit={handleSubmit} > {/* paper */} <section className="paper-section"> <div className="paper-card card-add-paper" around="xs"> <Subheader className="subheader submit-header"> Paper Information </Subheader> <div className="d-flex form-group"> <label>Title :</label> <Field name="title" component={CustomInput} fullWidth={true} hintText="Paper Title" /> </div> <div className="d-flex form-group"> <label className="mt30">Abstract :</label> <Field name="abstract" component={CustomInput} fullWidth={true} multiLine rows={2} hintText="Paper Abstract" /> </div> <div className="d-flex form-group"> <label>Keywords :</label> <Field name="keywords" component={CustomInput} fullWidth={true} multiLine rows={1} hintText="Paper keywords" /> </div> <div className="d-flex form-group"> <label>Topic :</label> <Field name="topic" component={renderSelectField} hintText="Paper Topic" fullWidth={true} > {topics.map(topic => { return ( <MenuItem key={topic.id} value={topic.id} primaryText={topic.name} /> ); })} </Field> </div> <div className="d-flex form-group file-field"> <label>File :</label> <Field name="file" component={FileInput} onChange={handleUploadFile} /> </div> </div> </section> {/* paper */} {/* corresponser */} <section className="paper-section"> <div className="paper-card card-add-paper" around="xs"> <Subheader className="subheader submit-header"> Address For Correspondence </Subheader> <div className="d-flex form-group"> <label>Street :</label> <Field name="street" component={CustomInput} fullWidth={true} hintText="Enter the street" /> </div> <div className="d-flex form-group"> <label>City :</label> <Field name="city" component={CustomInput} fullWidth={true} hintText="Enter the city" /> </div> <div className="d-flex form-group"> <label>Country :</label> <Field name="country" component={renderSelectField} fullWidth={true} hintText="Choose the country" > {countryData.map(country => { return ( <MenuItem key={country.label} value={country.label} primaryText={country.label} /> ); })} </Field> </div> <div className="d-flex form-group"> <label>Zipcode :</label> <Field name="zipcode" component={CustomInput} fullWidth={true} hintText="Enter the zipcode" /> </div> </div> </section> {/* corresponser */} {/* author */} <FieldArray name="editAuthors" component={EditAuthors} authors={this.props.initialValues} /> {/* author */} <div style={{ marginBottom: '20px' }} className="d-flex save-btn btn-group" > <RaisedButton label="Save" primary={true} type="submit" disabled={pristine} className="mr15" /> <RaisedButton label="Cancel" style={{ marginLeft: '10px' }} containerElement={<Link to="/conference/papers" />} /> </div> </form> ); } } export default reduxForm({ form: 'EditPaperForm', validate, })(EditPaperForm);
src/components/table-item.js
waywaaard/spectacle
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { getStyles } from '../utils/base'; import Radium from 'radium'; @Radium export default class TableItem extends Component { render() { const typefaceStyle = this.context.typeface || {}; return ( <td className={this.props.className} style={[this.context.styles.components.tableItem, getStyles.call(this), this.props.style, typefaceStyle]}> {this.props.children} </td> ); } } TableItem.propTypes = { children: PropTypes.node, className: PropTypes.string, style: PropTypes.object }; TableItem.contextTypes = { styles: PropTypes.object, store: PropTypes.object, typeface: PropTypes.object };
test/pages/search.js
MoveOnOrg/mop-frontend
import React from 'react' import { expect } from 'chai' import { shallow } from 'enzyme' import { createMockStore } from 'redux-test-utils' import SearchPage from '../../src/containers/search' describe('<SearchPage />', () => { const baseStore = createMockStore({ userStore: {} }) it('renders default values with no search query', () => { const searchPageProps = { query: {}, location: { query: { } } } const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />) expect(context.props().query).to.equal('') expect(context.props().pageNumber).to.equal('1') expect(context.props().selectState).to.equal('') }) it('parses out query', () => { const searchPageProps = { query: {}, location: { query: { q: 'cats' } } } const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />) expect(context.props().query).to.equal('cats') expect(context.props().pageNumber).to.equal('1') expect(context.props().selectState).to.equal('') }) it('parses out page number', () => { const searchPageProps = { query: {}, location: { query: { q: 'cats', page: '2' } } } const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />) expect(context.props().query).to.equal('cats') expect(context.props().pageNumber).to.equal('2') expect(context.props().selectState).to.equal('') }) it('parses out selected state', () => { const searchPageProps = { query: {}, location: { query: { q: 'cats', page: '2', state: 'VA' } } } const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />) expect(context.props().query).to.equal('cats') expect(context.props().pageNumber).to.equal('2') expect(context.props().selectState).to.equal('VA') }) })
ui/shared/utils/constants.js
macarthur-lab/seqr
import React from 'react' import { Form } from 'semantic-ui-react' import orderBy from 'lodash/orderBy' import flatten from 'lodash/flatten' import { validators } from '../components/form/ReduxFormWrapper' import { BooleanCheckbox, RadioGroup, Dropdown, Select, InlineToggle, Pagination, BaseSemanticInput, } from '../components/form/Inputs' import BaseFieldView from '../components/panel/view-fields/BaseFieldView' import OptionFieldView from '../components/panel/view-fields/OptionFieldView' import ListFieldView from '../components/panel/view-fields/ListFieldView' import SingleFieldView from '../components/panel/view-fields/SingleFieldView' import TagFieldView from '../components/panel/view-fields/TagFieldView' import { stripMarkdown } from './stringUtils' import { ColoredIcon } from '../components/StyledComponents' export const GENOME_VERSION_37 = '37' export const GENOME_VERSION_38 = '38' export const GENOME_VERSION_OPTIONS = [ { value: GENOME_VERSION_37, text: 'GRCh37' }, { value: GENOME_VERSION_38, text: 'GRCh38' }, ] export const GENOME_VERSION_LOOKUP = GENOME_VERSION_OPTIONS.reduce((acc, { value, text }) => ({ ...acc, [value]: text }), {}) export const GENOME_VERSION_FIELD = { name: 'genomeVersion', label: 'Genome Version', component: RadioGroup, options: GENOME_VERSION_OPTIONS, } export const GENOME_VERSION_DISPLAY_LOOKUP = { GRCh37: 'hg19', GRCh38: 'hg38', } // PROJECT FIELDS export const EDITABLE_PROJECT_FIELDS = [ { name: 'name', label: 'Project Name', placeholder: 'Name', validate: validators.required, autoFocus: true }, { name: 'description', label: 'Project Description', placeholder: 'Description' }, ] export const PROJECT_FIELDS = [ ...EDITABLE_PROJECT_FIELDS, GENOME_VERSION_FIELD, ] const MAILTO_CONTACT_URL_REGEX = /^mailto:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}(,\s*[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{1,4})*$/i export const MATCHMAKER_CONTACT_NAME_FIELD = { label: 'Contact Name' } export const MATCHMAKER_CONTACT_URL_FIELD = { label: 'Contact URL', parse: val => `mailto:${val}`, format: val => (val || '').replace('mailto:', ''), validate: val => (MAILTO_CONTACT_URL_REGEX.test(val) ? undefined : 'Invalid contact url'), } // SAMPLES export const DATASET_TYPE_VARIANT_CALLS = 'VARIANTS' export const DATASET_TYPE_SV_CALLS = 'SV' export const SAMPLE_TYPE_EXOME = 'WES' export const SAMPLE_TYPE_GENOME = 'WGS' export const SAMPLE_TYPE_RNA = 'RNA' export const SAMPLE_TYPE_OPTIONS = [ { value: SAMPLE_TYPE_EXOME, text: 'Exome' }, { value: SAMPLE_TYPE_GENOME, text: 'Genome' }, { value: SAMPLE_TYPE_RNA, text: 'RNA-seq' }, ] export const SAMPLE_TYPE_LOOKUP = SAMPLE_TYPE_OPTIONS.reduce( (acc, opt) => ({ ...acc, ...{ [opt.value]: opt }, }), {}, ) // ANALYSIS STATUS export const FAMILY_STATUS_SOLVED = 'S' export const FAMILY_STATUS_SOLVED_KNOWN_GENE_KNOWN_PHENOTYPE = 'S_kgfp' export const FAMILY_STATUS_SOLVED_KNOWN_GENE_DIFFERENT_PHENOTYPE = 'S_kgdp' export const FAMILY_STATUS_SOLVED_NOVEL_GENE = 'S_ng' export const FAMILY_STATUS_STRONG_CANDIDATE_KNOWN_GENE_KNOWN_PHENOTYPE = 'Sc_kgfp' export const FAMILY_STATUS_STRONG_CANDIDATE_KNOWN_GENE_DIFFERENT_PHENOTYPE = 'Sc_kgdp' export const FAMILY_STATUS_STRONG_CANDIDATE_NOVEL_GENE = 'Sc_ng' export const FAMILY_STATUS_REVIEWED_PURSUING_CANDIDATES = 'Rcpc' export const FAMILY_STATUS_REVIEWED_NO_CLEAR_CANDIDATE = 'Rncc' export const FAMILY_STATUS_CLOSED = 'C' export const FAMILY_STATUS_ANALYSIS_IN_PROGRESS = 'I' const FAMILY_STATUS_WAITING_FOR_DATA = 'Q' export const FAMILY_ANALYSIS_STATUS_OPTIONS = [ { value: FAMILY_STATUS_SOLVED, color: '#4CAF50', name: 'Solved' }, { value: FAMILY_STATUS_SOLVED_KNOWN_GENE_KNOWN_PHENOTYPE, color: '#4CAF50', name: 'Solved - known gene for phenotype' }, { value: FAMILY_STATUS_SOLVED_KNOWN_GENE_DIFFERENT_PHENOTYPE, color: '#4CAF50', name: 'Solved - gene linked to different phenotype' }, { value: FAMILY_STATUS_SOLVED_NOVEL_GENE, color: '#4CAF50', name: 'Solved - novel gene' }, { value: FAMILY_STATUS_STRONG_CANDIDATE_KNOWN_GENE_KNOWN_PHENOTYPE, color: '#CDDC39', name: 'Strong candidate - known gene for phenotype' }, { value: FAMILY_STATUS_STRONG_CANDIDATE_KNOWN_GENE_DIFFERENT_PHENOTYPE, color: '#CDDC39', name: 'Strong candidate - gene linked to different phenotype' }, { value: FAMILY_STATUS_STRONG_CANDIDATE_NOVEL_GENE, color: '#CDDC39', name: 'Strong candidate - novel gene' }, { value: FAMILY_STATUS_REVIEWED_PURSUING_CANDIDATES, color: '#CDDC39', name: 'Reviewed, currently pursuing candidates' }, { value: FAMILY_STATUS_REVIEWED_NO_CLEAR_CANDIDATE, color: '#EF5350', name: 'Reviewed, no clear candidate' }, { value: FAMILY_STATUS_CLOSED, color: '#9c0502', name: 'Closed, no longer under analysis' }, { value: FAMILY_STATUS_ANALYSIS_IN_PROGRESS, color: '#4682B4', name: 'Analysis in Progress' }, { value: FAMILY_STATUS_WAITING_FOR_DATA, color: '#FFC107', name: 'Waiting for data' }, ] export const FAMILY_ANALYSIS_STATUS_LOOKUP = FAMILY_ANALYSIS_STATUS_OPTIONS.reduce((acc, tag) => { return { [tag.value]: tag, ...acc } }, {}) // SUCCESS STORY const FAMILY_SUCCESS_STORY_NOVEL_DISCOVERY = 'N' const FAMILY_SUCCESS_STORY_ALTERED_CLINICAL_OUTCOME = 'A' const FAMILY_SUCCESS_STORY_COLLABORATION = 'C' const FAMILY_SUCCESS_STORY_TECHNICAL_WIN = 'T' const FAMILY_SUCCESS_STORY_DATA_SHARING = 'D' const FAMILY_SUCCESS_STORY_OTHER = 'O' export const FAMILY_SUCCESS_STORY_TYPE_OPTIONS = [ { value: FAMILY_SUCCESS_STORY_NOVEL_DISCOVERY, color: '#019143', name: 'Novel Discovery' }, { value: FAMILY_SUCCESS_STORY_ALTERED_CLINICAL_OUTCOME, color: '#FFAB57', name: 'Altered Clinical Outcome' }, { value: FAMILY_SUCCESS_STORY_COLLABORATION, color: '#833E7D', name: 'Collaboration' }, { value: FAMILY_SUCCESS_STORY_TECHNICAL_WIN, color: '#E76013', name: 'Technical Win' }, { value: FAMILY_SUCCESS_STORY_DATA_SHARING, color: '#6583EC', name: 'Data Sharing' }, { value: FAMILY_SUCCESS_STORY_OTHER, color: '#5D5D5F', name: 'Other' }, ] export const FAMILY_SUCCESS_STORY_TYPE_OPTIONS_LOOKUP = FAMILY_SUCCESS_STORY_TYPE_OPTIONS.reduce((acc, tag) => { return { [tag.value]: tag, ...acc } }, {}) export const successStoryTypeDisplay = tag => <span> <ColoredIcon name="stop" color={FAMILY_SUCCESS_STORY_TYPE_OPTIONS_LOOKUP[tag].color} /> {FAMILY_SUCCESS_STORY_TYPE_OPTIONS_LOOKUP[tag].name} </span> // FAMILY FIELDS export const FAMILY_FIELD_ID = 'familyId' export const FAMILY_DISPLAY_NAME = 'displayName' export const FAMILY_FIELD_DESCRIPTION = 'description' export const FAMILY_FIELD_ANALYSIS_STATUS = 'analysisStatus' export const FAMILY_FIELD_ASSIGNED_ANALYST = 'assignedAnalyst' export const FAMILY_FIELD_ANALYSED_BY = 'analysedBy' export const FAMILY_FIELD_SUCCESS_STORY_TYPE = 'successStoryTypes' export const FAMILY_FIELD_SUCCESS_STORY = 'successStory' export const FAMILY_FIELD_ANALYSIS_NOTES = 'analysisNotes' export const FAMILY_FIELD_ANALYSIS_SUMMARY = 'analysisSummary' export const FAMILY_FIELD_MME_NOTES = 'mmeNotes' export const FAMILY_FIELD_INTERNAL_NOTES = 'internalCaseReviewNotes' export const FAMILY_FIELD_INTERNAL_SUMMARY = 'internalCaseReviewSummary' export const FAMILY_FIELD_FIRST_SAMPLE = 'firstSample' export const FAMILY_FIELD_CODED_PHENOTYPE = 'codedPhenotype' export const FAMILY_FIELD_OMIM_NUMBER = 'postDiscoveryOmimNumber' export const FAMILY_FIELD_PMIDS = 'pubmedIds' export const FAMILY_FIELD_PEDIGREE = 'pedigreeImage' export const FAMILY_FIELD_CREATED_DATE = 'createdDate' export const FAMILY_FIELD_RENDER_LOOKUP = { [FAMILY_FIELD_DESCRIPTION]: { name: 'Family Description' }, [FAMILY_FIELD_ANALYSIS_STATUS]: { name: 'Analysis Status', component: OptionFieldView }, [FAMILY_FIELD_ASSIGNED_ANALYST]: { name: 'Assigned Analyst', component: BaseFieldView, submitArgs: { familyField: 'assigned_analyst' }, }, [FAMILY_FIELD_ANALYSED_BY]: { name: 'Analysed By', component: BaseFieldView, submitArgs: { familyField: 'analysed_by' }, }, [FAMILY_FIELD_SUCCESS_STORY_TYPE]: { name: 'Success Story Type', component: TagFieldView, internal: true, }, [FAMILY_FIELD_SUCCESS_STORY]: { name: 'Success Story', internal: true }, [FAMILY_FIELD_FIRST_SAMPLE]: { name: 'Data Loaded?', component: BaseFieldView }, [FAMILY_FIELD_ANALYSIS_NOTES]: { name: 'Notes' }, [FAMILY_FIELD_ANALYSIS_SUMMARY]: { name: 'Analysis Summary' }, [FAMILY_FIELD_MME_NOTES]: { name: 'Matchmaker Notes' }, [FAMILY_FIELD_CODED_PHENOTYPE]: { name: 'Coded Phenotype', component: SingleFieldView }, [FAMILY_FIELD_OMIM_NUMBER]: { name: 'Post-discovery OMIM #', component: SingleFieldView }, [FAMILY_FIELD_PMIDS]: { name: 'Publications on this discovery', component: ListFieldView }, [FAMILY_FIELD_INTERNAL_NOTES]: { name: 'Internal Notes', internal: true }, [FAMILY_FIELD_INTERNAL_SUMMARY]: { name: 'Internal Summary', internal: true }, } export const FAMILY_DETAIL_FIELDS = [ { id: FAMILY_FIELD_DESCRIPTION, canEdit: true }, { id: FAMILY_FIELD_ANALYSIS_STATUS, canEdit: true }, { id: FAMILY_FIELD_ASSIGNED_ANALYST, canEdit: true, collaboratorEdit: true }, { id: FAMILY_FIELD_ANALYSED_BY, canEdit: true, collaboratorEdit: true }, { id: FAMILY_FIELD_SUCCESS_STORY_TYPE, canEdit: true }, { id: FAMILY_FIELD_SUCCESS_STORY, canEdit: true }, { id: FAMILY_FIELD_ANALYSIS_NOTES, canEdit: true }, { id: FAMILY_FIELD_ANALYSIS_SUMMARY, canEdit: true }, { id: FAMILY_FIELD_MME_NOTES, canEdit: true }, { id: FAMILY_FIELD_CODED_PHENOTYPE, canEdit: true }, { id: FAMILY_FIELD_OMIM_NUMBER, canEdit: true }, { id: FAMILY_FIELD_PMIDS, canEdit: true }, ] // INDIVIDUAL FIELDS export const SEX_OPTIONS = [ { value: 'M', text: 'Male' }, { value: 'F', text: 'Female' }, { value: 'U', text: '?' }, ] export const SEX_LOOKUP = SEX_OPTIONS.reduce( (acc, opt) => ({ ...acc, ...{ [opt.value]: opt.text === '?' ? 'Unknown' : opt.text }, }), {}, ) export const AFFECTED = 'A' export const UNAFFECTED = 'N' export const UNKNOWN_AFFECTED = 'U' export const AFFECTED_OPTIONS = [ { value: AFFECTED, text: 'Affected' }, { value: UNAFFECTED, text: 'Unaffected' }, { value: UNKNOWN_AFFECTED, text: '?' }, ] export const AFFECTED_LOOKUP = AFFECTED_OPTIONS.reduce( (acc, opt) => ({ ...acc, ...{ [opt.value]: opt.text === '?' ? 'Unknown' : opt.text }, }), {}, ) export const PROBAND_RELATIONSHIP_OPTIONS = [ { value: 'S', name: 'Self' }, { value: 'M', name: 'Mother' }, { value: 'F', name: 'Father' }, { value: 'B', name: 'Sibling' }, { value: 'C', name: 'Child' }, { value: 'H', name: 'Maternal Half Sibling' }, { value: 'J', name: 'Paternal Half Sibling' }, { value: 'G', name: 'Maternal Grandmother' }, { value: 'W', name: 'Maternal Grandfather' }, { value: 'X', name: 'Paternal Grandmother' }, { value: 'Y', name: 'Paternal Grandfather' }, { value: 'A', name: 'Maternal Aunt' }, { value: 'L', name: 'Maternal Uncle' }, { value: 'E', name: 'Paternal Aunt' }, { value: 'D', name: 'Paternal Uncle' }, { value: 'N', name: 'Niece' }, { value: 'P', name: 'Nephew' }, { value: 'Z', name: 'Maternal 1st Cousin' }, { value: 'K', name: 'Paternal 1st Cousin' }, { value: 'O', name: 'Other' }, { value: 'U', name: 'Unknown' }, ] const PROBAND_RELATIONSHIP_LOOKUP = PROBAND_RELATIONSHIP_OPTIONS.reduce( (acc, opt) => ({ ...acc, ...{ [opt.value]: opt.name }, }), {}, ) export const INDIVIDUAL_FIELD_ID = 'individualId' export const INDIVIDUAL_FIELD_PATERNAL_ID = 'paternalId' export const INDIVIDUAL_FIELD_MATERNAL_ID = 'maternalId' export const INDIVIDUAL_FIELD_SEX = 'sex' export const INDIVIDUAL_FIELD_AFFECTED = 'affected' export const INDIVIDUAL_FIELD_NOTES = 'notes' export const INDIVIDUAL_FIELD_PROBAND_RELATIONSHIP = 'probandRelationship' export const INDIVIDUAL_FIELD_CONFIGS = { [FAMILY_FIELD_ID]: { label: 'Family ID' }, [INDIVIDUAL_FIELD_ID]: { label: 'Individual ID' }, [INDIVIDUAL_FIELD_PATERNAL_ID]: { label: 'Paternal ID', description: 'Individual ID of the father' }, [INDIVIDUAL_FIELD_MATERNAL_ID]: { label: 'Maternal ID', description: 'Individual ID of the mother' }, [INDIVIDUAL_FIELD_SEX]: { label: 'Sex', format: sex => SEX_LOOKUP[sex], width: 3, description: 'Male or Female, leave blank if unknown', formFieldProps: { component: RadioGroup, options: SEX_OPTIONS }, }, [INDIVIDUAL_FIELD_AFFECTED]: { label: 'Affected Status', format: affected => AFFECTED_LOOKUP[affected], width: 4, description: 'Affected or Unaffected, leave blank if unknown', formFieldProps: { component: RadioGroup, options: AFFECTED_OPTIONS }, }, [INDIVIDUAL_FIELD_NOTES]: { label: 'Notes', format: stripMarkdown, description: 'free-text notes related to this individual' }, [INDIVIDUAL_FIELD_PROBAND_RELATIONSHIP]: { label: 'Proband Relation', description: `Relationship of the individual to the family proband. Can be one of: ${ PROBAND_RELATIONSHIP_OPTIONS.map(({ name }) => name).join(', ')}`, format: relationship => PROBAND_RELATIONSHIP_LOOKUP[relationship], formFieldProps: { component: Select, options: PROBAND_RELATIONSHIP_OPTIONS, search: true }, }, } export const INDIVIDUAL_HPO_EXPORT_DATA = [ { header: 'HPO Terms (present)', field: 'features', format: features => (features ? features.map(feature => `${feature.id} (${feature.label})`).join('; ') : ''), description: 'comma-separated list of HPO Terms for present phenotypes in this individual', }, { header: 'HPO Terms (absent)', field: 'absentFeatures', format: features => (features ? features.map(feature => `${feature.id} (${feature.label})`).join('; ') : ''), description: 'comma-separated list of HPO Terms for phenotypes not present in this individual', }, ] export const familyVariantSamples = (family, individualsByGuid, samplesByGuid) => { const sampleGuids = [...(family.individualGuids || []).map(individualGuid => individualsByGuid[individualGuid]).reduce( (acc, individual) => new Set([...acc, ...(individual.sampleGuids || [])]), new Set(), )] const loadedSamples = sampleGuids.map(sampleGuid => samplesByGuid[sampleGuid]) return orderBy(loadedSamples, [s => s.loadedDate], 'asc') } // CLINVAR export const CLINSIG_SEVERITY = { // clinvar pathogenic: 1, 'risk factor': 0, risk_factor: 0, 'likely pathogenic': 1, 'pathogenic/likely_pathogenic': 1, likely_pathogenic: 1, benign: -1, 'likely benign': -1, 'benign/likely_benign': -1, likely_benign: -1, protective: -1, // hgmd DM: 1, 'DM?': 0, FPV: 0, FP: 0, DFP: 0, DP: 0, } // LOCUS LISTS export const LOCUS_LIST_NAME_FIELD = 'name' export const LOCUS_LIST_NUM_ENTRIES_FIELD = 'numEntries' export const LOCUS_LIST_DESCRIPTION_FIELD = 'description' export const LOCUS_LIST_IS_PUBLIC_FIELD_NAME = 'isPublic' export const LOCUS_LIST_LAST_MODIFIED_FIELD_NAME = 'lastModifiedDate' export const LOCUS_LIST_CURATOR_FIELD_NAME = 'createdBy' export const LOCUS_LIST_FIELDS = [ { name: LOCUS_LIST_NAME_FIELD, label: 'List Name', labelHelp: 'A descriptive name for this gene list', validate: value => (value ? undefined : 'Name is required'), width: 3, isEditable: true, }, { name: LOCUS_LIST_NUM_ENTRIES_FIELD, label: 'Entries', width: 1 }, { name: LOCUS_LIST_DESCRIPTION_FIELD, label: 'Description', labelHelp: 'Some background on how this list is curated', width: 9, isEditable: true, }, { name: LOCUS_LIST_LAST_MODIFIED_FIELD_NAME, label: 'Last Updated', width: 3, fieldDisplay: lastModifiedDate => new Date(lastModifiedDate).toLocaleString('en-US', { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }), }, { name: LOCUS_LIST_CURATOR_FIELD_NAME, label: 'Curator', width: 3 }, { name: LOCUS_LIST_IS_PUBLIC_FIELD_NAME, label: 'Public List', labelHelp: 'Should other seqr users be able to use this gene list?', component: RadioGroup, options: [{ value: true, text: 'Yes' }, { value: false, text: 'No' }], fieldDisplay: isPublic => (isPublic ? 'Yes' : 'No'), width: 2, isEditable: true, }, ] export const LOCUS_LIST_ITEMS_FIELD = { name: 'rawItems', label: 'Genes/ Intervals', labelHelp: 'A list of genes and intervals. Can be separated by commas or whitespace. Intervals should be in the form <chrom>:<start>-<end>', fieldDisplay: () => null, isEditable: true, component: Form.TextArea, rows: 12, validate: value => (value ? undefined : 'Genes and/or intervals are required'), additionalFormFields: [ { name: 'intervalGenomeVersion', component: RadioGroup, options: GENOME_VERSION_OPTIONS, label: 'Genome Version', labelHelp: 'The genome version associated with intervals. Only required if the list contains intervals', validate: (value, allValues) => ( (value || !(allValues.rawItems || '').match(/([^\s-]*):(\d*)-(\d*)/)) ? undefined : 'Genome version is required for lists with intervals' ), }, { name: 'ignoreInvalidItems', component: BooleanCheckbox, label: 'Ignore invalid genes and intervals', }, ], } export const VEP_GROUP_NONSENSE = 'nonsense' export const VEP_GROUP_ESSENTIAL_SPLICE_SITE = 'essential_splice_site' export const VEP_GROUP_EXTENDED_SPLICE_SITE = 'extended_splice_site' export const VEP_GROUP_MISSENSE = 'missense' export const VEP_GROUP_FRAMESHIFT = 'frameshift' export const VEP_GROUP_INFRAME = 'in_frame' export const VEP_GROUP_SYNONYMOUS = 'synonymous' export const VEP_GROUP_OTHER = 'other' export const VEP_GROUP_SV = 'structural' const ORDERED_VEP_CONSEQUENCES = [ { description: 'A feature ablation whereby the deleted region includes a transcript feature', text: 'Transcript ablation', value: 'transcript_ablation', so: 'SO:0001893', }, { description: "A splice variant that changes the 2 base region at the 5' end of an intron", text: 'Splice donor variant', value: 'splice_donor_variant', group: VEP_GROUP_ESSENTIAL_SPLICE_SITE, so: 'SO:0001575', }, { description: "A splice variant that changes the 2 base region at the 3' end of an intron", text: 'Splice acceptor variant', value: 'splice_acceptor_variant', group: VEP_GROUP_ESSENTIAL_SPLICE_SITE, so: 'SO:0001574', }, { description: 'A sequence variant whereby at least one base of a codon is changed, resulting in a premature stop codon, leading to a shortened transcript', text: 'Stop gained', value: 'stop_gained', group: VEP_GROUP_NONSENSE, so: 'SO:0001587', }, { description: 'A sequence variant which causes a disruption of the translational reading frame, because the number of nucleotides inserted or deleted is not a multiple of three', text: 'Frameshift', value: 'frameshift_variant', group: VEP_GROUP_FRAMESHIFT, so: 'SO:0001589', }, { description: 'A large deletion', text: 'Deletion', value: 'DEL', group: VEP_GROUP_SV, }, { description: 'A large duplication', text: 'Duplication', value: 'DUP', group: VEP_GROUP_SV, }, { description: 'A sequence variant where at least one base of the terminator codon (stop) is changed, resulting in an elongated transcript', text: 'Stop lost', value: 'stop_lost', group: VEP_GROUP_MISSENSE, so: 'SO:0001578', }, { description: 'A codon variant that changes at least one base of the first codon of a transcript', text: 'Initiator codon', value: 'initiator_codon_variant', group: VEP_GROUP_MISSENSE, so: 'SO:0001582', }, { description: 'A codon variant that changes at least one base of the canonical start codon.', text: 'Start lost', value: 'start_lost', group: VEP_GROUP_MISSENSE, so: 'SO:0002012', }, { description: 'An inframe non synonymous variant that inserts bases into in the coding sequence', text: 'In frame insertion', value: 'inframe_insertion', group: VEP_GROUP_INFRAME, so: 'SO:0001821', }, { description: 'An inframe non synonymous variant that deletes bases from the coding sequence', text: 'In frame deletion', value: 'inframe_deletion', group: VEP_GROUP_INFRAME, so: 'SO:0001822', }, { description: 'A feature amplification of a region containing a transcript', text: 'Transcript amplification', value: 'transcript_amplification', so: 'SO:0001889', }, { description: 'A sequence_variant which is predicted to change the protein encoded in the coding sequence', text: 'Protein Altering', value: 'protein_altering_variant', group: VEP_GROUP_MISSENSE, so: 'SO:0001818', }, { description: 'A sequence variant, where the change may be longer than 3 bases, and at least one base of a codon is changed resulting in a codon that encodes for a different amino acid', text: 'Missense', value: 'missense_variant', group: VEP_GROUP_MISSENSE, so: 'SO:0001583', }, { description: 'A sequence variant in which a change has occurred within the region of the splice site, either within 1-3 bases of the exon or 3-8 bases of the intron', text: 'Splice region', value: 'splice_region_variant', group: VEP_GROUP_EXTENDED_SPLICE_SITE, so: 'SO:0001630', }, { description: 'A sequence variant where at least one base of the final codon of an incompletely annotated transcript is changed', text: 'Incomplete terminal codon variant', value: 'incomplete_terminal_codon_variant', so: 'SO:0001626', }, { description: 'A sequence variant where there is no resulting change to the encoded amino acid', text: 'Synonymous', value: 'synonymous_variant', group: VEP_GROUP_SYNONYMOUS, so: 'SO:0001819', }, { description: 'A sequence variant where at least one base in the terminator codon is changed, but the terminator remains', text: 'Stop retained', value: 'stop_retained_variant', group: VEP_GROUP_SYNONYMOUS, so: 'SO:0001567', }, { description: 'A sequence variant that changes the coding sequence', text: 'Coding sequence variant', value: 'coding_sequence_variant', so: 'SO:0001580', }, { description: 'A transcript variant located with the sequence of the mature miRNA', text: 'Mature miRNA variant', value: 'mature_miRNA_variant', so: 'SO:0001620', }, { description: "A UTR variant of the 5' UTR", text: '5 prime UTR variant', value: '5_prime_UTR_variant', so: 'SO:0001623', }, { description: "A UTR variant of the 3' UTR", text: '3 prime UTR variant', value: '3_prime_UTR_variant', so: 'SO:0001624', }, { description: 'A transcript variant occurring within an intron', text: 'Intron variant', value: 'intron_variant', so: 'SO:0001627', }, { description: 'A variant in a transcript that is the target of NMD', text: 'NMD transcript variant', value: 'NMD_transcript_variant', so: 'SO:0001621', }, //2 kinds of 'non_coding_transcript_exon_variant' text due to value change in Ensembl v77 { description: 'A sequence variant that changes non-coding exon sequence', text: 'Non-coding exon variant', value: 'non_coding_exon_variant', so: 'SO:0001792', }, { description: 'A sequence variant that changes non-coding exon sequence', text: 'Non-coding transcript exon variant', value: 'non_coding_transcript_exon_variant', so: 'SO:0001792', }, // 2 kinds of 'nc_transcript_variant' text due to value change in Ensembl v77 { description: 'A transcript variant of a non coding RNA', text: 'nc transcript variant', value: 'nc_transcript_variant', so: 'SO:0001619', }, { description: 'A transcript variant of a non coding RNA', text: 'Non-coding transcript variant', value: 'non_coding_transcript_variant', so: 'SO:0001619', }, { description: 'A feature ablation whereby the deleted region includes a transcription factor binding site', text: 'TFBS ablation', value: 'TFBS_ablation', so: 'SO:0001895', }, { description: 'A feature amplification of a region containing a transcription factor binding site', text: 'TFBS amplification', value: 'TFBS_amplification', so: 'SO:0001892', }, { description: 'In regulatory region annotated by Ensembl', text: 'TF binding site variant', value: 'TF_binding_site_variant', so: 'SO:0001782', }, { description: 'A sequence variant located within a regulatory region', text: 'Regulatory region variant', value: 'regulatory_region_variant', so: 'SO:0001566', }, { description: 'A feature ablation whereby the deleted region includes a regulatory region', text: 'Regulatory region ablation', value: 'regulatory_region_ablation', so: 'SO:0001894', }, { description: 'A feature amplification of a region containing a regulatory region', text: 'Regulatory region amplification', value: 'regulatory_region_amplification', so: 'SO:0001891', }, { description: 'A sequence variant that causes the extension of a genomic feature, with regard to the reference sequence', text: 'Feature elongation', value: 'feature_elongation', so: 'SO:0001907', }, { description: 'A sequence variant that causes the reduction of a genomic feature, with regard to the reference sequence', text: 'Feature truncation', value: 'feature_truncation', so: 'SO:0001906', }, { description: 'A sequence variant located in the intergenic region, between genes', text: 'Intergenic variant', value: 'intergenic_variant', so: 'SO:0001628', }, ] export const GROUPED_VEP_CONSEQUENCES = ORDERED_VEP_CONSEQUENCES.reduce((acc, consequence) => { const group = consequence.group || VEP_GROUP_OTHER acc[group] = [...(acc[group] || []), consequence] return acc }, {}) export const VEP_CONSEQUENCE_ORDER_LOOKUP = ORDERED_VEP_CONSEQUENCES.reduce((acc, consequence, i) => ({ ...acc, [consequence.value]: i }), {}) export const SHOW_ALL = 'ALL' export const NOTE_TAG_NAME = 'Has Notes' export const EXCLUDED_TAG_NAME = 'Excluded' export const REVIEW_TAG_NAME = 'Review' export const KNOWN_GENE_FOR_PHENOTYPE_TAG_NAME = 'Known gene for phenotype' export const DISCOVERY_CATEGORY_NAME = 'CMG Discovery Tags' export const SORT_BY_FAMILY_GUID = 'FAMILY_GUID' export const SORT_BY_XPOS = 'XPOS' const SORT_BY_PATHOGENICITY = 'PATHOGENICITY' const SORT_BY_IN_OMIM = 'IN_OMIM' const SORT_BY_PROTEIN_CONSQ = 'PROTEIN_CONSEQUENCE' const SORT_BY_GNOMAD = 'GNOMAD' const SORT_BY_EXAC = 'EXAC' const SORT_BY_1KG = '1KG' const SORT_BY_CONSTRAINT = 'CONSTRAINT' const SORT_BY_CADD = 'CADD' const SORT_BY_REVEL = 'REVEL' const SORT_BY_SPLICE_AI = 'SPLICE_AI' const SORT_BY_EIGEN = 'EIGEN' const SORT_BY_MPC = 'MPC' const SORT_BY_PRIMATE_AI = 'PRIMATE_AI' const clinsigSeverity = (variant, user) => { const { clinvar = {}, hgmd = {} } = variant const clinvarSignificance = clinvar.clinicalSignificance && clinvar.clinicalSignificance.split('/')[0] const hgmdSignificance = user.isStaff && hgmd.class if (!clinvarSignificance && !hgmdSignificance) return -10 let clinvarSeverity = 0.1 if (clinvarSignificance) { clinvarSeverity = clinvarSignificance in CLINSIG_SEVERITY ? CLINSIG_SEVERITY[clinvarSignificance] + 1 : 0.5 } const hgmdSeverity = hgmdSignificance in CLINSIG_SEVERITY ? CLINSIG_SEVERITY[hgmdSignificance] + 0.5 : 0 return clinvarSeverity + hgmdSeverity } export const MISSENSE_THRESHHOLD = 3 export const LOF_THRESHHOLD = 0.35 const getGeneConstraintSortScore = ({ constraints }) => { if (!constraints || constraints.louef === undefined) { return Infinity } let missenseOffset = constraints.misZ > MISSENSE_THRESHHOLD ? constraints.misZ : 0 if (constraints.louef > LOF_THRESHHOLD) { missenseOffset /= MISSENSE_THRESHHOLD } return constraints.louef - missenseOffset } const populationComparator = population => (a, b) => ((a.populations || {})[population] || {}).af - ((b.populations || {})[population] || {}).af const predictionComparator = prediction => (a, b) => ((b.predictions || {})[prediction] || -1) - ((a.predictions || {})[prediction] || -1) const getConsequenceRank = ({ transcripts, svType }) => ( transcripts ? Math.min(...Object.values(transcripts || {}).flat().map(({ majorConsequence }) => VEP_CONSEQUENCE_ORDER_LOOKUP[majorConsequence]).filter(val => val)) : VEP_CONSEQUENCE_ORDER_LOOKUP[svType] ) const VARIANT_SORT_OPTONS = [ { value: SORT_BY_FAMILY_GUID, text: 'Family', comparator: (a, b) => a.familyGuids[0].localeCompare(b.familyGuids[0]) }, { value: SORT_BY_XPOS, text: 'Position', comparator: (a, b) => a.xpos - b.xpos }, { value: SORT_BY_PROTEIN_CONSQ, text: 'Protein Consequence', comparator: (a, b) => getConsequenceRank(a) - getConsequenceRank(b), }, { value: SORT_BY_GNOMAD, text: 'gnomAD Genomes Frequency', comparator: populationComparator('gnomad_genomes') }, { value: SORT_BY_EXAC, text: 'ExAC Frequency', comparator: populationComparator('exac') }, { value: SORT_BY_1KG, text: '1kg Frequency', comparator: populationComparator('g1k') }, { value: SORT_BY_CADD, text: 'Cadd', comparator: predictionComparator('cadd') }, { value: SORT_BY_REVEL, text: 'Revel', comparator: predictionComparator('revel') }, { value: SORT_BY_EIGEN, text: 'Eigen', comparator: predictionComparator('eigen') }, { value: SORT_BY_MPC, text: 'MPC', comparator: predictionComparator('mpc') }, { value: SORT_BY_SPLICE_AI, text: 'Splice AI', comparator: predictionComparator('splice_ai') }, { value: SORT_BY_PRIMATE_AI, text: 'Primate AI', comparator: predictionComparator('primate_ai') }, { value: SORT_BY_PATHOGENICITY, text: 'Pathogenicity', comparator: (a, b, geneId, user) => clinsigSeverity(b, user) - clinsigSeverity(a, user) }, { value: SORT_BY_CONSTRAINT, text: 'Constraint', comparator: (a, b, genesById) => Math.min(...Object.keys(a.transcripts || {}).reduce((acc, geneId) => [...acc, getGeneConstraintSortScore(genesById[geneId] || {})], [])) - Math.min(...Object.keys(b.transcripts || {}).reduce((acc, geneId) => [...acc, getGeneConstraintSortScore(genesById[geneId] || {})], [])), }, { value: SORT_BY_IN_OMIM, text: 'In OMIM', comparator: (a, b, genesById) => Object.keys(b.transcripts || {}).reduce( (acc, geneId) => (genesById[geneId] ? acc + genesById[geneId].omimPhenotypes.length : acc), 0) - Object.keys(a.transcripts || {}).reduce( (acc, geneId) => (genesById[geneId] ? acc + genesById[geneId].omimPhenotypes.length : acc), 0), }, ] const VARIANT_SORT_OPTONS_NO_FAMILY_SORT = VARIANT_SORT_OPTONS.slice(1) export const VARIANT_SORT_LOOKUP = VARIANT_SORT_OPTONS.reduce( (acc, opt) => ({ ...acc, [opt.value]: opt.comparator, }), {}, ) const BASE_VARIANT_SORT_FIELD = { name: 'sort', component: Dropdown, inline: true, selection: false, fluid: false, label: 'Sort By:', } export const VARIANT_SORT_FIELD = { ...BASE_VARIANT_SORT_FIELD, options: VARIANT_SORT_OPTONS } export const VARIANT_SORT_FIELD_NO_FAMILY_SORT = { ...BASE_VARIANT_SORT_FIELD, options: VARIANT_SORT_OPTONS_NO_FAMILY_SORT } export const VARIANT_HIDE_EXCLUDED_FIELD = { name: 'hideExcluded', component: InlineToggle, label: 'Hide Excluded', labelHelp: 'Remove all variants tagged with the "Excluded" tag from the results', } export const VARIANT_HIDE_REVIEW_FIELD = { name: 'hideReviewOnly', component: InlineToggle, label: 'Hide Review Only', labelHelp: 'Remove all variants tagged with only the "Review" tag from the results', } export const VARIANT_HIDE_KNOWN_GENE_FOR_PHENOTYPE_FIELD = { name: 'hideKnownGeneForPhenotype', component: InlineToggle, label: 'Hide Known Gene For Phenotype', labelHelp: 'Remove all variants tagged with the "Known Gene For Phenotype" tag from the results', } export const VARIANT_PER_PAGE_FIELD = { name: 'recordsPerPage', component: Dropdown, inline: true, selection: false, fluid: false, label: 'Variants Per Page:', options: [{ value: 10 }, { value: 25 }, { value: 50 }, { value: 100 }], } export const VARIANT_PAGINATION_FIELD = { name: 'page', component: Pagination, size: 'mini', siblingRange: 0, firstItem: null, lastItem: null, format: val => parseInt(val, 10), } export const VARIANT_TAGGED_DATE_FIELD = { name: 'taggedAfter', component: BaseSemanticInput, inputType: 'Input', label: 'Tagged After', type: 'date', inline: true, } export const PREDICTION_INDICATOR_MAP = { D: { color: 'red', value: 'damaging' }, A: { color: 'red', value: 'disease causing' }, T: { color: 'green', value: 'tolerated' }, N: { color: 'green', value: 'polymorphism' }, P: { color: 'green', value: 'polymorphism' }, B: { color: 'green', value: 'benign' }, } export const POLYPHEN_MAP = { D: { value: 'probably damaging' }, P: { color: 'yellow', value: 'possibly damaging' }, } export const MUTTASTER_MAP = { D: { value: 'disease causing' }, } export const getVariantMainGeneId = ({ transcripts = {}, mainTranscriptId, selectedMainTranscriptId }) => { if (selectedMainTranscriptId || mainTranscriptId) { return (Object.entries(transcripts).find(entry => entry[1].some(({ transcriptId }) => transcriptId === (selectedMainTranscriptId || mainTranscriptId)), ) || [])[0] } if (Object.keys(transcripts).length === 1 && Object.values(transcripts)[0] && Object.values(transcripts)[0].length === 0) { return Object.keys(transcripts)[0] } return null } export const getVariantMainTranscript = ({ transcripts = {}, mainTranscriptId, selectedMainTranscriptId }) => flatten(Object.values(transcripts)).find( ({ transcriptId }) => transcriptId === (selectedMainTranscriptId || mainTranscriptId), ) || {} const getPopAf = population => (variant) => { const populationData = (variant.populations || {})[population] return (populationData || {}).af } export const VARIANT_EXPORT_DATA = [ { header: 'chrom' }, { header: 'pos' }, { header: 'ref' }, { header: 'alt' }, { header: 'gene', getVal: variant => getVariantMainTranscript(variant).geneSymbol }, { header: 'worst_consequence', getVal: variant => getVariantMainTranscript(variant).majorConsequence }, { header: '1kg_freq', getVal: getPopAf('g1k') }, { header: 'exac_freq', getVal: getPopAf('exac') }, { header: 'gnomad_genomes_freq', getVal: getPopAf('gnomad_genomes') }, { header: 'gnomad_exomes_freq', getVal: getPopAf('gnomad_exomes') }, { header: 'topmed_freq', getVal: getPopAf('topmed') }, { header: 'cadd', getVal: variant => (variant.predictions || {}).cadd }, { header: 'revel', getVal: variant => (variant.predictions || {}).revel }, { header: 'eigen', getVal: variant => (variant.predictions || {}).eigen }, { header: 'splice_ai', getVal: variant => (variant.predictions || {}).splice_ai }, { header: 'polyphen', getVal: variant => (MUTTASTER_MAP[(variant.predictions || {}).polyphen] || PREDICTION_INDICATOR_MAP[(variant.predictions || {}).polyphen] || {}).value }, { header: 'sift', getVal: variant => (PREDICTION_INDICATOR_MAP[(variant.predictions || {}).sift] || {}).value }, { header: 'muttaster', getVal: variant => (MUTTASTER_MAP[(variant.predictions || {}).mut_taster] || PREDICTION_INDICATOR_MAP[(variant.predictions || {}).mut_taster] || {}).value }, { header: 'fathmm', getVal: variant => (PREDICTION_INDICATOR_MAP[(variant.predictions || {}).fathmm] || {}).value }, { header: 'rsid', getVal: variant => variant.rsid }, { header: 'hgvsc', getVal: variant => getVariantMainTranscript(variant).hgvsc }, { header: 'hgvsp', getVal: variant => getVariantMainTranscript(variant).hgvsp }, { header: 'clinvar_clinical_significance', getVal: variant => (variant.clinvar || {}).clinicalSignificance }, { header: 'clinvar_gold_stars', getVal: variant => (variant.clinvar || {}).goldStars }, { header: 'filter', getVal: variant => variant.genotypeFilters }, { header: 'family', getVal: variant => variant.familyGuids[0].split(/_(.+)/)[1] }, { header: 'tags', getVal: (variant, tagsByGuid) => (tagsByGuid[variant.variantGuid] || []).map(tag => tag.name).join('|') }, { header: 'notes', getVal: (variant, tagsByGuid, notesByGuid) => (notesByGuid[variant.variantGuid] || []).map(note => `${note.createdBy}: ${note.note.replace(/\n/g, ' ')}`).join('|') }, ] export const ALL_INHERITANCE_FILTER = 'all' export const RECESSIVE_FILTER = 'recessive' export const HOM_RECESSIVE_FILTER = 'homozygous_recessive' export const X_LINKED_RECESSIVE_FILTER = 'x_linked_recessive' export const COMPOUND_HET_FILTER = 'compound_het' export const DE_NOVO_FILTER = 'de_novo' export const ANY_AFFECTED = 'any_affected' export const INHERITANCE_FILTER_OPTIONS = [ { value: ALL_INHERITANCE_FILTER, text: 'All' }, { value: RECESSIVE_FILTER, text: 'Recessive', detail: 'This method identifies genes with any evidence of recessive variation. It is the union of all variants returned by the homozygous recessive, x-linked recessive, and compound heterozygous methods.', }, { value: HOM_RECESSIVE_FILTER, color: 'transparent', // Adds an empty label so option is indented text: 'Homozygous Recessive', detail: 'Finds variants where all affected individuals are Alt / Alt and each of their parents Heterozygous.', }, { value: X_LINKED_RECESSIVE_FILTER, color: 'transparent', // Adds an empty label so option is indented text: 'X-Linked Recessive', detail: "Recessive inheritance on the X Chromosome. This is similar to the homozygous recessive search, but a proband's father must be homozygous reference. (This is how hemizygous genotypes are called by current variant calling methods.)", }, { value: COMPOUND_HET_FILTER, color: 'transparent', // Adds an empty label so option is indented text: 'Compound Heterozygous', detail: 'Affected individual(s) have two heterozygous mutations in the same gene on opposite haplotypes. Unaffected individuals cannot have the same combination of alleles as affected individuals, or be homozygous alternate for any of the variants. If parents are not present, this method only searches for pairs of heterozygous variants; they may not be on different haplotypes.', }, { value: DE_NOVO_FILTER, text: 'De Novo/ Dominant', detail: 'Finds variants where all affected indivs have at least one alternate allele and all unaffected are homozygous reference.', }, { value: ANY_AFFECTED, text: 'Any Affected', detail: 'Finds variants where at least one affected individual has at least one alternate allele.', }, ] // Users export const USER_NAME_FIELDS = [ { name: 'firstName', label: 'First Name', width: 8, inline: true, }, { name: 'lastName', label: 'Last Name', width: 8, inline: true, }, ]
docs/app/Examples/elements/Container/Variations/ContainerExampleAlignment.js
shengnian/shengnian-ui-react
/* eslint-disable max-len */ import React from 'react' import { Container, Divider } from 'shengnian-ui-react' const ContainerExampleAlignment = () => ( <div> <Container textAlign='left'> Left Aligned </Container> <Container textAlign='center'> Center Aligned </Container> <Container textAlign='right'> Right Aligned </Container> <Container textAlign='justified'> <b>Justified</b> <Divider /> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa strong. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede link mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa strong. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede link mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi.</p> </Container> </div> ) export default ContainerExampleAlignment
test/ModalSpec.js
natlownes/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Modal from '../src/Modal'; import { render, shouldWarn } from './helpers'; describe('Modal', function () { let mountPoint; beforeEach(() => { mountPoint = document.createElement('div'); document.body.appendChild(mountPoint); }); afterEach(function () { React.unmountComponentAtNode(mountPoint); document.body.removeChild(mountPoint); }); it('Should render the modal content', function() { let noOp = function () {}; let instance = render( <Modal show onHide={noOp} animation={false}> <strong>Message</strong> </Modal> , mountPoint); assert.ok( ReactTestUtils.findRenderedDOMComponentWithTag(instance.refs.modal, 'strong')); }); it('Should add modal-open class to the modal container while open', function(done) { let Container = React.createClass({ getInitialState() { return { modalOpen: true }; }, handleCloseModal() { this.setState({ modalOpen: false }); }, render() { return ( <div> <Modal animation={false} show={this.state.modalOpen} onHide={this.handleCloseModal} container={this} > <strong>Message</strong> </Modal> </div> ); } }); let instance = render( <Container /> , mountPoint); let modal = ReactTestUtils.findRenderedComponentWithType(instance, Modal); assert.ok(React.findDOMNode(instance).className.match(/\bmodal-open\b/)); let backdrop = React.findDOMNode(modal.refs.backdrop); ReactTestUtils.Simulate.click(backdrop); setTimeout(function() { assert.equal(React.findDOMNode(instance).className.length, 0); done(); }, 0); }); it('Should close the modal when the backdrop is clicked', function (done) { let doneOp = function () { done(); }; let instance = render( <Modal show onHide={doneOp} animation={false}> <strong>Message</strong> </Modal> , mountPoint); let backdrop = React.findDOMNode(instance.refs.backdrop); ReactTestUtils.Simulate.click(backdrop); }); it('Should close the modal when the modal dialog is clicked', function (done) { let doneOp = function () { done(); }; let instance = render( <Modal show onHide={doneOp}> <strong>Message</strong> </Modal> , mountPoint); let dialog = React.findDOMNode(instance.refs.dialog); ReactTestUtils.Simulate.click(dialog); }); it('Should not close the modal when the "static" backdrop is clicked', function () { let onHideSpy = sinon.spy(); let instance = render( <Modal show onHide={onHideSpy} backdrop='static'> <strong>Message</strong> </Modal> , mountPoint); let backdrop = React.findDOMNode(instance.refs.backdrop); ReactTestUtils.Simulate.click(backdrop); expect(onHideSpy).to.not.have.been.called; }); it('Should close the modal when the modal close button is clicked', function (done) { let doneOp = function () { done(); }; let instance = render( <Modal show onHide={doneOp}> <Modal.Header closeButton /> <strong>Message</strong> </Modal> , mountPoint); let button = React.findDOMNode(instance.refs.modal) .getElementsByClassName('close')[0]; ReactTestUtils.Simulate.click(button); }); it('Should pass className to the dialog', function () { let noOp = function () {}; let instance = render( <Modal show className='mymodal' onHide={noOp}> <strong>Message</strong> </Modal> , mountPoint); let dialog = React.findDOMNode(instance.refs.dialog); assert.ok(dialog.className.match(/\bmymodal\b/)); }); it('Should use bsClass on the dialog', function () { let noOp = function () {}; let instance = render( <Modal show bsClass='mymodal' onHide={noOp}> <strong>Message</strong> </Modal> , mountPoint); let dialog = React.findDOMNode(instance.refs.dialog); let backdrop = React.findDOMNode(instance.refs.backdrop); assert.ok(dialog.className.match(/\bmymodal\b/)); assert.ok(dialog.children[0].className.match(/\bmymodal-dialog\b/)); assert.ok(dialog.children[0].children[0].className.match(/\bmymodal-content\b/)); assert.ok(backdrop.className.match(/\bmymodal-backdrop\b/)); shouldWarn("Invalid prop 'bsClass' of value 'mymodal'"); }); it('Should pass bsSize to the dialog', function () { let noOp = function () {}; let instance = render( <Modal show bsSize='small' onHide={noOp}> <strong>Message</strong> </Modal> , mountPoint); let dialog = React.findDOMNode(instance.refs.modal).getElementsByClassName('modal-dialog')[0]; assert.ok(dialog.className.match(/\bmodal-sm\b/)); }); it('Should pass dialogClassName to the dialog', function () { let noOp = function () {}; let instance = render( <Modal show dialogClassName="testCss" onHide={noOp}> <strong>Message</strong> </Modal> , mountPoint); let dialog = ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.modal, 'modal-dialog'); assert.match(dialog.props.className, /\btestCss\b/); }); it('Should assign refs correctly when no backdrop', function () { let test = () => render( <Modal show backdrop={false} onHide={function () {}}> <strong>Message</strong> </Modal> , mountPoint); expect(test).not.to.throw(); }); it('Should use dialogComponent', function () { let noOp = function () {}; class CustomDialog { render() { return <div {...this.props}/>; } } let instance = render( <Modal show dialogComponent={CustomDialog} onHide={noOp}> <strong>Message</strong> </Modal> , mountPoint); assert.ok(instance.refs.dialog instanceof CustomDialog); }); it('Should pass transition callbacks to Transition', function (done) { let count = 0; let increment = ()=> count++; let instance = render( <Modal show onHide={() => {}} onExit={increment} onExiting={increment} onExited={()=> { increment(); expect(count).to.equal(6); done(); }} onEnter={increment} onEntering={increment} onEntered={()=> { increment(); instance.setProps({ show: false }); }} > <strong>Message</strong> </Modal> , mountPoint); }); it('Should unbind listeners when unmounted', function() { render( <div> <Modal show onHide={() => null} animation={false}> <strong>Foo bar</strong> </Modal> </div> , mountPoint); assert.include(document.body.className, 'modal-open'); render(<div />, mountPoint); assert.notInclude(document.body.className, 'modal-open'); }); describe('Focused state', function () { let focusableContainer = null; beforeEach(() => { focusableContainer = document.createElement('div'); focusableContainer.tabIndex = 0; document.body.appendChild(focusableContainer); focusableContainer.focus(); }); afterEach(function () { React.unmountComponentAtNode(focusableContainer); document.body.removeChild(focusableContainer); }); it('Should focus on the Modal when it is opened', function () { document.activeElement.should.equal(focusableContainer); let instance = render( <Modal show onHide={() => {}} animation={false}> <strong>Message</strong> </Modal> , focusableContainer); document.activeElement.className.should.contain('modal'); instance.renderWithProps({ show: false }); document.activeElement.should.equal(focusableContainer); }); it('Should not focus on the Modal when autoFocus is false', function () { render( <Modal show autoFocus={false} onHide={() => {}} animation={false}> <strong>Message</strong> </Modal> , focusableContainer); document.activeElement.should.equal(focusableContainer); }); it('Should not focus Modal when child has focus', function () { document.activeElement.should.equal(focusableContainer); render( <Modal show onHide={() => {}} animation={false}> <input autoFocus /> </Modal> , focusableContainer); let input = document.getElementsByTagName('input')[0]; document.activeElement.should.equal(input); }); }); });
src/index.js
iTrollu/trollapp
import React from 'react'; import { render } from 'react-dom'; import App from './components/App'; import 'babel-polyfill'; render( <App />, document.querySelector('#root') );
github/src/users/UserListItem.js
changjianhong/react-native-redux
import React from 'react'; import { View, Text, TouchableOpacity, Image, StyleSheet } from 'react-native'; import { Heading1 } from '../components/Text'; import Button from 'apsl-react-native-button'; class UserListItem extends React.Component { render() { const {login, avatar_url} = this.props.data; const {onPress} = this.props; return ( <TouchableOpacity style={styles.container} onPress={onPress}> <Image source={{uri: avatar_url}} style={styles.icon} /> <View style={styles.rightContainer}> <Heading1>{login}</Heading1> <View style={styles.rightBottomContainer}> <View style={{flexDirection: 'row', height:28}}> <Button style={[styles.button, {width: 40}]} textStyle={styles.buttonTextStyle} allowFontScaling={true}>repo</Button> <Button style={styles.button} textStyle={styles.buttonTextStyle} allowFontScaling={true}>starred</Button> <Button style={styles.button} textStyle={styles.buttonTextStyle} allowFontScaling={true}>followers</Button> </View> </View> </View> </TouchableOpacity> ) } } const styles = StyleSheet.create({ container: { flexDirection: 'row', borderBottomWidth: 1, borderColor: '#e0e0e0' }, icon: { margin: 8, width: 40, height: 40, borderRadius:4 }, rightContainer: { flex: 1, marginTop: 4, }, rightBottomContainer: { flex: 1, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'flex-end', }, button: { borderColor: 'transparent', width: 60, height: 20, borderRadius: 0, }, buttonTextStyle: { fontSize: 12, color: '#777777', textAlign: 'left' } }) export default UserListItem;
app/javascript/mastodon/features/compose/index.js
foozmeat/mastodon
import React from 'react'; import ComposeFormContainer from './containers/compose_form_container'; import NavigationContainer from './containers/navigation_container'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import { mountCompose, unmountCompose } from '../../actions/compose'; import { Link } from 'react-router-dom'; import { injectIntl, defineMessages } from 'react-intl'; import SearchContainer from './containers/search_container'; import Motion from '../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import SearchResultsContainer from './containers/search_results_container'; import { changeComposing } from '../../actions/compose'; const messages = defineMessages({ start: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, community: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, logout: { id: 'navigation_bar.logout', defaultMessage: 'Logout' }, }); const mapStateToProps = state => ({ columns: state.getIn(['settings', 'columns']), showSearch: state.getIn(['search', 'submitted']) && !state.getIn(['search', 'hidden']), }); @connect(mapStateToProps) @injectIntl export default class Compose extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, columns: ImmutablePropTypes.list.isRequired, multiColumn: PropTypes.bool, showSearch: PropTypes.bool, intl: PropTypes.object.isRequired, }; componentDidMount () { this.props.dispatch(mountCompose()); } componentWillUnmount () { this.props.dispatch(unmountCompose()); } onFocus = () => { this.props.dispatch(changeComposing(true)); } onBlur = () => { this.props.dispatch(changeComposing(false)); } render () { const { multiColumn, showSearch, intl } = this.props; let header = ''; if (multiColumn) { const { columns } = this.props; header = ( <nav className='drawer__header'> <Link to='/getting-started' className='drawer__tab' title={intl.formatMessage(messages.start)} aria-label={intl.formatMessage(messages.start)}><i role='img' className='fa fa-fw fa-asterisk' /></Link> {!columns.some(column => column.get('id') === 'HOME') && ( <Link to='/timelines/home' className='drawer__tab' title={intl.formatMessage(messages.home_timeline)} aria-label={intl.formatMessage(messages.home_timeline)}><i role='img' className='fa fa-fw fa-home' /></Link> )} {!columns.some(column => column.get('id') === 'NOTIFICATIONS') && ( <Link to='/notifications' className='drawer__tab' title={intl.formatMessage(messages.notifications)} aria-label={intl.formatMessage(messages.notifications)}><i role='img' className='fa fa-fw fa-bell' /></Link> )} {!columns.some(column => column.get('id') === 'COMMUNITY') && ( <Link to='/timelines/public/local' className='drawer__tab' title={intl.formatMessage(messages.community)} aria-label={intl.formatMessage(messages.community)}><i role='img' className='fa fa-fw fa-users' /></Link> )} {!columns.some(column => column.get('id') === 'PUBLIC') && ( <Link to='/timelines/public' className='drawer__tab' title={intl.formatMessage(messages.public)} aria-label={intl.formatMessage(messages.public)}><i role='img' className='fa fa-fw fa-globe' /></Link> )} <a href='/settings/preferences' className='drawer__tab' title={intl.formatMessage(messages.preferences)} aria-label={intl.formatMessage(messages.preferences)}><i role='img' className='fa fa-fw fa-cog' /></a> <a href='/auth/sign_out' className='drawer__tab' data-method='delete' title={intl.formatMessage(messages.logout)} aria-label={intl.formatMessage(messages.logout)}><i role='img' className='fa fa-fw fa-sign-out' /></a> </nav> ); } return ( <div className='drawer'> {header} <SearchContainer /> <div className='drawer__pager'> <div className='drawer__inner' onFocus={this.onFocus}> <NavigationContainer onClose={this.onBlur} /> <ComposeFormContainer /> {multiColumn && <div className='mastodon' />} </div> <Motion defaultStyle={{ x: -100 }} style={{ x: spring(showSearch ? 0 : -100, { stiffness: 210, damping: 20 }) }}> {({ x }) => <div className='drawer__inner darker' style={{ transform: `translateX(${x}%)`, visibility: x === -100 ? 'hidden' : 'visible' }}> <SearchResultsContainer /> </div> } </Motion> </div> </div> ); } }
packages/material-ui-icons/src/WorkOff.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M23 21.74l-1.46-1.46L7.21 5.95 3.25 1.99 1.99 3.25l2.7 2.7h-.64c-1.11 0-1.99.89-1.99 2l-.01 11c0 1.11.89 2 2 2h15.64L21.74 23 23 21.74zM22 7.95c.05-1.11-.84-2-1.95-1.95h-4V3.95c0-1.11-.89-2-2-1.95h-4c-1.11-.05-2 .84-2 1.95v.32l13.95 14V7.95zM14.05 6H10V3.95h4.05V6z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment> , 'WorkOff');
src/svg-icons/maps/local-post-office.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPostOffice = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/> </SvgIcon> ); MapsLocalPostOffice = pure(MapsLocalPostOffice); MapsLocalPostOffice.displayName = 'MapsLocalPostOffice'; MapsLocalPostOffice.muiName = 'SvgIcon'; export default MapsLocalPostOffice;
index.android.js
daikon-db/daikon-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class daikon extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('daikon', () => daikon);
src/components/proof.js
barrierandco/barrierandco
import React from 'react' import styled from 'styled-components' import fitbot from '../assets/images/proof-fitbot.png' import mideo from '../assets/images/proof-mideo.png' import Button from './button' import Cell from './cell' const ProofContainer = styled.div` margin: 40px 0 0; @media ${props => props.theme.breakpoint} { margin: 176px 0 40px; } ` const ProofDribbble = styled.div` margin-top: 24px; text-align: center; @media ${props => props.theme.breakpoint} { margin-top: 40px; } ` const ProofImage = styled.figure` border-radius: ${props => props.theme.borderRadius}; box-shadow: ${props => props.theme.boxShadow}; margin: 24px 0; overflow: hidden; position: relative; @media ${props => props.theme.breakpoint} { box-shadow: none; float: left; margin: ${props => props.left ? '40px -10% 0 0' : '120px 0 0 0'}; overflow: visible; width: 55%; } a { color: inherit; } figcaption { background: white; padding: 16px 24px; @media ${props => props.theme.breakpoint} { background: none; margin-top: 16px; padding: 0; width: ${props => props.left ? '75%' : '100%'}; } } img { display: block; width: 100%; @media ${props => props.theme.breakpoint} { border-radius: ${props => props.theme.borderRadius}; box-shadow: ${props => props.theme.boxShadow}; } } p { line-height: 1.1; margin-bottom: 0; } small { font-family: 'Roboto', 'Helvetica Neue', Helvetica, sans-serif; font-size: 0.85rem; opacity: 0.6; @media ${props => props.theme.breakpoint} { font-size: 0.6rem; } } strong { display: block; line-height: 1; margin-bottom: 8px; } ` const ProofGallery = styled.div` &::after { clear: both; content: ''; display: table; } ` const Proof = props => <ProofContainer> <Cell> <h2>Need proof of completed projects, not&nbsp;just&nbsp;blueprints?</h2> <p>Having completed over three dozen individual projects, I’ve experienced a wide array of project types, styles and purposes. Here are some samples of the work I am most proud to show you. <strong>A personal goal of mine is to do my job so well that I put myself out of business.</strong> This means that I want to get you set up so that you can hire your own team and continue growing without needing to keep expensive consultancies on retainer as your dream&nbsp;becomes&nbsp;reality.</p> </Cell> <ProofGallery> <ProofImage left> <img src={fitbot} alt="sample image of the fitbot ios design project" /> <figcaption> <p> <strong>Fitbot iOS App</strong> <small><a href="http://bit.ly/2xNNpts">Fitbot</a> needed a better way for clients to communicate with their coaches. To resolve this roadblock, I designed an iOS app that prioritized communication throughout the entire experience.</small> </p> </figcaption> </ProofImage> <ProofImage right> <img src={mideo} alt="sample image of the mideo web application design and development project" /> <figcaption> <p> <strong>Mideo Web Application</strong> <small>Using React, Redux and Google's Firebase, I designed and developed the entire application for Mideo which allows filmmakers to sample an entire library of songs on their videos <em>before purchasing the songs</em>.</small> </p> </figcaption> </ProofImage> </ProofGallery> <ProofDribbble> <Button href="http://bit.ly/2ysGEdB" icon="dribbble" dribbble>See more on Dribbble</Button> </ProofDribbble> </ProofContainer> export default Proof
packages/app/app/components/LibraryView/LibraryHeader/index.js
nukeop/nuclear
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { Button } from 'semantic-ui-react'; import { withTranslation } from 'react-i18next'; import { withHandlers, withState, compose } from 'recompose'; import Header from '../../Header'; import LibraryFolders from '../LibraryFolders'; import styles from './styles.scss'; const LibraryHeader = ({ t, collapsed, toggleCollapsed, ...rest }) => ( <> <div className={cx( styles.library_header_row, { collapsed } )}> <Header>{ t('header') }</Header> <Button basic icon={`chevron ${collapsed ? 'down' : 'up'}`} onClick={toggleCollapsed} /> </div> { !collapsed && <LibraryFolders {...rest}/> } </> ); LibraryHeader.propTypes = { collapsed: PropTypes.bool, setCollapsed: PropTypes.func }; LibraryHeader.defaultProps = { collapsed: false, setCollapsed: () => {} }; export default compose( withTranslation('library'), withState('collapsed', 'setCollapsed', false), withHandlers({ toggleCollapsed: ({ collapsed, setCollapsed }) => () => setCollapsed(!collapsed) }) )(LibraryHeader);
node_modules/react-bootstrap/es/MenuItem.js
mohammed52/something.pk
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 all from 'prop-types-extra/lib/all'; import SafeAnchor from './SafeAnchor'; import { bsClass, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { /** * Highlight the menu item as active. */ active: PropTypes.bool, /** * Disable the menu item, making it unselectable. */ disabled: PropTypes.bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: all(PropTypes.bool, function (_ref) { var divider = _ref.divider, children = _ref.children; return divider && children ? new Error('Children will not be rendered for dividers') : null; }), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: PropTypes.any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: PropTypes.bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: PropTypes.func }; var defaultProps = { divider: false, disabled: false, header: false }; var MenuItem = function (_React$Component) { _inherits(MenuItem, _React$Component); function MenuItem(props, context) { _classCallCheck(this, MenuItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } MenuItem.prototype.handleClick = function handleClick(event) { var _props = this.props, href = _props.href, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; MenuItem.prototype.render = function render() { var _props2 = this.props, active = _props2.active, disabled = _props2.disabled, divider = _props2.divider, header = _props2.header, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['active', 'disabled', 'divider', 'header', 'onClick', 'className', 'style']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['eventKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return React.createElement('li', _extends({}, elementProps, { role: 'separator', className: classNames(className, 'divider'), style: style })); } if (header) { return React.createElement('li', _extends({}, elementProps, { role: 'heading', className: classNames(className, prefix(bsProps, 'header')), style: style })); } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, elementProps, { role: 'menuitem', tabIndex: '-1', onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return MenuItem; }(React.Component); MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; export default bsClass('dropdown', MenuItem);
test/TabbedAreaSpec.js
zerkms/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import TabbedArea from '../src/TabbedArea'; import NavItem from '../src/NavItem'; import TabPane from '../src/TabPane'; import ValidComponentChildren from '../src/utils/ValidComponentChildren'; describe('TabbedArea', function () { it('Should show the correct tab', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea activeKey={1}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.equal(panes[0].props.active, true); assert.equal(panes[1].props.active, false); let tabbedArea = ReactTestUtils.findRenderedComponentWithType(instance, TabbedArea); assert.equal(tabbedArea.refs.tabs.props.activeKey, 1); }); it('Should only show the tabs with `TabPane.props.tab` set', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea activeKey={3}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane eventKey={2}>Tab 2 content</TabPane> <TabPane tab="Tab 2" eventKey={3}>Tab 3 content</TabPane> </TabbedArea> ); let tabbedArea = ReactTestUtils.findRenderedComponentWithType(instance, TabbedArea); assert.equal(ValidComponentChildren.numberOf(instance.refs.tabs.props.children), 2); assert.equal(tabbedArea.refs.tabs.props.activeKey, 3); }); it('Should allow tab to have React components', function () { let tabTitle = ( <strong className="special-tab">Tab 2</strong> ); let instance = ReactTestUtils.renderIntoDocument( <TabbedArea activeKey={2}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab={tabTitle} eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.tabs, 'special-tab')); }); it('Should call onSelect when tab is selected', function (done) { function onSelect(key) { assert.equal(key, '2'); done(); } let tab2 = <span className="tab2">Tab2</span>; let instance = ReactTestUtils.renderIntoDocument( <TabbedArea onSelect={onSelect} activeKey={1}> <TabPane tab="Tab 1" eventKey='1'>Tab 1 content</TabPane> <TabPane tab={tab2} eventKey='2'>Tab 2 content</TabPane> </TabbedArea> ); ReactTestUtils.Simulate.click( ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab2') ); }); it('Should have children with the correct DOM properties', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea activeKey={1}> <TabPane tab="Tab 1" className="custom" id="pane0id" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.ok(React.findDOMNode(panes[0]).className.match(/\bcustom\b/)); assert.equal(React.findDOMNode(panes[0]).id, 'pane0id'); }); it('Should show the correct initial pane', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea defaultActiveKey={2}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let tabbedArea = ReactTestUtils.findRenderedComponentWithType(instance, TabbedArea); let panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.equal(panes[0].props.active, false); assert.equal(panes[1].props.active, true); assert.equal(tabbedArea.refs.tabs.props.activeKey, 2); }); it('Should show the correct first tab with no active key value', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let tabbedArea = ReactTestUtils.findRenderedComponentWithType(instance, TabbedArea); let panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.equal(panes[0].props.active, true); assert.equal(panes[1].props.active, false); assert.equal(tabbedArea.refs.tabs.props.activeKey, 1); }); it('Should show the correct first tab with `React.Children.map` children values', function () { let panes = [ <div>Tab 1 content</div>, <div>Tab 2 content</div> ]; let paneComponents = React.Children.map(panes, function(child, index) { return <TabPane eventKey={index} tab={'Tab #' + index}>{child}</TabPane>; }); let instance = ReactTestUtils.renderIntoDocument( <TabbedArea> {paneComponents} {null} </TabbedArea> ); assert.equal(instance.refs.tabs.props.activeKey, 0); }); it('Should show the correct tab when selected', function () { let tab1 = <span className="tab1">Tab 1</span>; let instance = ReactTestUtils.renderIntoDocument( <TabbedArea defaultActiveKey={2} animation={false}> <TabPane tab={tab1} eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let tabbedArea = ReactTestUtils.findRenderedComponentWithType(instance, TabbedArea); let panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); ReactTestUtils.Simulate.click( ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1') ); assert.equal(panes[0].props.active, true); assert.equal(panes[1].props.active, false); assert.equal(tabbedArea.refs.tabs.props.activeKey, 1); }); it('Should pass default bsStyle (of "tabs") to Nav', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea defaultActiveKey={1} animation={false}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav-tabs')); }); it('Should pass bsStyle to Nav', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea bsStyle="pills" defaultActiveKey={1} animation={false}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav-pills')); }); it('Should pass className to rendered Tab NavItem', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea activeKey={3}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane className="pull-right" tab="Tab 2" eventKey={3}>Tab 3 content</TabPane> </TabbedArea> ); let tabPane = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.equal(tabPane.length, 2); assert.equal(React.findDOMNode(tabPane[1]).getAttribute('class').match(/pull-right/)[0], 'pull-right'); }); it('Should pass disabled to NavItem', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea activeKey={1}> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2} disabled={true}>Tab 2 content</TabPane> </TabbedArea> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled')); }); it('Should not show content when clicking disabled tab', function () { let tab1 = <span className="tab1">Tab 1</span>; let instance = ReactTestUtils.renderIntoDocument( <TabbedArea defaultActiveKey={2} animation={false}> <TabPane tab={tab1} eventKey={1} disabled={true}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let tabbedArea = ReactTestUtils.findRenderedComponentWithType(instance, TabbedArea); let panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); ReactTestUtils.Simulate.click( ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1') ); assert.equal(panes[0].props.active, false); assert.equal(panes[1].props.active, true); assert.equal(tabbedArea.refs.tabs.props.activeKey, 2); }); describe('Web Accessibility', function(){ it('Should generate ids from parent id', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea defaultActiveKey={2} id='tabs'> <TabPane tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem); tabs.every(tab => assert.ok(tab.props['aria-controls'] && tab.props.linkId)); }); it('Should add aria-controls', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea defaultActiveKey={2} id='tabs'> <TabPane id='pane-1' tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane id='pane-2' tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.equal(panes[0].props['aria-labelledby'], 'pane-1___tab'); assert.equal(panes[1].props['aria-labelledby'], 'pane-2___tab'); }); it('Should add aria-controls', function () { let instance = ReactTestUtils.renderIntoDocument( <TabbedArea defaultActiveKey={2} id='tabs'> <TabPane id='pane-1' tab="Tab 1" eventKey={1}>Tab 1 content</TabPane> <TabPane id='pane-2' tab="Tab 2" eventKey={2}>Tab 2 content</TabPane> </TabbedArea> ); let tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem); assert.equal(tabs[0].props['aria-controls'], 'pane-1'); assert.equal(tabs[1].props['aria-controls'], 'pane-2'); }); }); });
winearb/static/__tests__/date_test.js
REBradley/WineArb
jest.unmock('../react/js/components/date.js') import React from 'react'; import { shallow } from 'enzyme'; import { Date } from '../react/js/components/date.js'; describe('Date', () => { let wrapper; beforeEach(() => { wrapper = shallow(<Date date={'November 30, 2012'}/>); }); it('should exist', () => { expect(wrapper).toBeDefined(); }); it('should render its props in "Date" div tag', () => { expect(wrapper.find('div.Date').childAt(0).text()).toEqual('November 30, 2012'); }); });
jekyll-admin/src/containers/views/tests/documentnew.spec.js
mparlak/mparlak.github.io
import React from 'react'; import { shallow } from 'enzyme'; import { DocumentNew } from '../DocumentNew'; import Errors from '../../../components/Errors'; import Button from '../../../components/Button'; import { config, doc } from './fixtures'; const defaultProps = { errors: [], fieldChanged: false, updated: false, router: {}, route: {}, config: config, params: { collection_name: doc.collection } }; const setup = (props = defaultProps) => { const actions = { createDocument: jest.fn(), updateTitle: jest.fn(), updateBody: jest.fn(), updatePath: jest.fn(), clearErrors: jest.fn() }; const component = shallow(<DocumentNew {...actions} {...props} />); return { component, actions, saveButton: component.find(Button), errors: component.find(Errors), props }; }; describe('Containers::DocumentNew', () => { it('should not render error messages initially', () => { const { errors } = setup(); expect(errors.node).toBeFalsy(); }); it('should render error messages', () => { const { errors } = setup(Object.assign({}, defaultProps, { errors: ['The title field is required!'] })); expect(errors.node).toBeTruthy(); }); it('should not call createDocument if a field is not changed.', () => { const { saveButton, actions } = setup(); saveButton.simulate('click'); expect(actions.createDocument).not.toHaveBeenCalled(); }); it('should call createDocument if a field is changed.', () => { const { saveButton, actions } = setup(Object.assign({}, defaultProps, { fieldChanged: true })); saveButton.simulate('click'); expect(actions.createDocument).toHaveBeenCalled(); }); });
barebones_bbb/src/components/Webcam/Image.js
wasong/cmpt433
import React from 'react' import PropTypes from 'prop-types' import Radium from 'radium' const Image = ({ image, }) => ( <div> <img src={image} alt="webcam" /> </div> ) Image.propTypes = { image: PropTypes.string, } Image.defaultProps = { image: '', } export default Radium(Image)
ajax/libs/highcharts/3.0.2/highcharts.src.js
CyrusSUEN/cdnjs
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v3.0.2 (2013-06-05) * * (c) 2009-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ (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/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 = doc.documentElement.ontouchstart !== UNDEFINED, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () {}, charts = [], PRODUCT = 'Highcharts', VERSION = '3.0.2', // 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', /* * Empirical lowest possible opacities for TRACKER_FILL * 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) + ')', // invisible but clickable //TRACKER_FILL = 'rgba(192,192,192,0.5)', NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', MILLISECOND = 'millisecond', SECOND = 'second', MINUTE = 'minute', HOUR = 'hour', DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', // constants for attributes LINEAR_GRADIENT = 'linearGradient', STOPS = 'stops', STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used makeTime, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}; // The Highcharts namespace win.Highcharts = win.Highcharts ? error(16, true) : {}; /** * 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 */ function extend(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. * 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, len = arguments.length, ret = {}, doCopy = function (copy, original) { var value, key; for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // For each argument, extend the return for (i = 0; i < len; i++) { ret = doCopy(ret, arguments[i]); } return ret; } /** * Take an array and turn into a hash with even number arguments as keys and odd numbers as * values. Allows creating constants for commonly used style properties, attributes etc. * Avoid it in performance critical situations like looping */ function hash() { var i = 0, args = arguments, length = args.length, obj = {}; for (; i < length; i++) { obj[args[i++]] = args[i]; } return obj; } /** * 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 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, setAttribute = 'setAttribute', 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. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof 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) { 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; } /** * 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 */ function numberFormat(number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = number, c = decimals === -1 ? ((n || 0).toString().split('.')[1] || '').length : // preserve decimals (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 || 0).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) : ""); } /** * 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. */ function wrap(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); }; } /** * 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), 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 // 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; val = 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(''); } /** * 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, options) { var normalized, i; // 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 (options && options.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++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * 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. */ function normalizeTimeTickInterval(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]; } // 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); return { unitRange: interval, count: count, unitName: unit[0] }; } /** * 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 */ function getTimeTicks(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), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits[SECOND]) { // second minDate.setMilliseconds(0); 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; minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), timezoneOffset = useUTC ? 0 : (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950 // 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] === timezoneOffset; }), 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; } /** * Helper class that contains variuos counters that are local to the chart. */ function ChartCounters() { this.color = 0; this.symbol = 0; } ChartCounters.prototype = { /** * Wraps the color counter if it reaches the specified length. */ wrapColor: function (length) { if (this.color >= length) { this.color = 0; } }, /** * Wraps the symbol counter if it reaches the specified length. */ wrapSymbol: function (length) { if (this.symbol >= length) { this.symbol = 0; } } }; /** * 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 */ /*jslint white: true*/ timeUnits = hash( MILLISECOND, 1, SECOND, 1000, MINUTE, 60000, HOUR, 3600000, DAY, 24 * 3600000, WEEK, 7 * 24 * 3600000, MONTH, 31 * 24 * 3600000, YEAR, 31556952000 ); /*jslint white: false*/ /** * 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) { 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, Step = Fx.step, dSetter, Tween = $.Tween, propHooks = Tween && Tween.propHooks, opacityHook = $.cssHooks.opacity; /*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 = Step, base, elem; // 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 = 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) { // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // 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(opacityHook, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) dSetter = 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)); }; // jQuery 1.8 style if (Tween) { propHooks.d = { set: dSetter }; // pre 1.8 } else { // animate paths Step.d = dSetter; } /** * 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 = 0, len = arr.length; for (; 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 (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; }; }, /** * 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 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; } 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(); $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { $(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 = 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 * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#666', cursor: 'default', fontSize: '11px', lineHeight: '14px' } }; defaultOptions = { colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a'], 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, canvasToolsURL: 'http://code.highcharts.com/3.0.2/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/3.0.2/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: 5, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, 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: 15, style: { color: '#274b6d',//#3E576F', fontSize: '16px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', y: 30, style: { color: '#4d759e' } }, 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, 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 //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { enabled: false, formatter: function () { return numberFormat(this.y, -1); }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // 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: true, states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 } }, select: { marker: {} } }, stickyTracking: true //tooltip: { //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <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: 1, borderColor: '#909090', borderRadius: 5, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 10, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { cursor: 'pointer', color: '#274b6d', fontSize: '12px' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, 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: '1em' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(255, 255, 255, .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' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', shadow: true, //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 useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; 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) { // Pull out axis options and apply them to the respective default axis options /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis); defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis); options.xAxis = options.yAxis = UNDEFINED;*/ // Merge in the default options defaultOptions = merge(defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Merely exposing defaultOptions for outside modules * isn't enough because the setOptions method creates 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 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 = /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*\)/.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.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 = { /** * 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; /** * A collection of attribute setters. These methods, if defined, are called right before a certain * attribute is set on an element wrapper. Returning false prevents the default attribute * setter to run. Returning a value causes the default setter to set that value. Used in * Renderer.label. */ wrapper.attrSetters = {}; }, /** * Default base for animation */ opacity: 1, /** * 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); 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(); } } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var wrapper = this, key, value, result, i, child, element = wrapper.element, nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text" renderer = wrapper.renderer, skipAttr, titleNode, attrSetters = wrapper.attrSetters, shadows = wrapper.shadows, hasSetSymbolSize, doTransform, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (isString(hash)) { key = hash; if (nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } else if (key === 'strokeWidth') { key = 'stroke-width'; } ret = attr(element, key) || wrapper[key] || 0; if (key !== 'd' && key !== 'visibility') { // 'd' is string in animation step ret = parseFloat(ret); } // setter } else { for (key in hash) { skipAttr = false; // reset value = hash[key]; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false) { if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // paths if (key === 'd') { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } //wrapper.d = value; // shortcut for animations // update child tspans x values } else if (key === 'x' && nodeName === 'text') { for (i = 0; i < element.childNodes.length; i++) { child = element.childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (attr(child, 'x') === attr(element, 'x')) { //child.setAttribute('x', value); attr(child, 'x', value); } } } else if (wrapper.rotation && (key === 'x' || key === 'y')) { doTransform = true; // apply gradients } else if (key === 'fill') { value = renderer.color(value, element, key); // circle x and y } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) { key = { x: 'cx', y: 'cy' }[key] || key; // rectangle border radius } else if (nodeName === 'rect' && key === 'r') { attr(element, { rx: value, ry: value }); skipAttr = true; // translation and text rotation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' || key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') { doTransform = true; skipAttr = true; // apply opacity as subnode (required by legacy WebKit and Batik) } else if (key === 'stroke') { value = renderer.color(value, element, key); // emulate VML's dashstyle implementation } else if (key === 'dashstyle') { key = 'stroke-dasharray'; value = value && value.toLowerCase(); if (value === 'solid') { value = NONE; } else 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]) * hash['stroke-width']; } value = value.join(','); } // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2 // is unable to cast them. Test again with final IE9. } else if (key === 'width') { value = pInt(value); // Text alignment } else if (key === 'align') { key = 'text-anchor'; value = { left: 'start', center: 'middle', right: 'end' }[value]; // Title requires a subnode, #431 } else if (key === 'title') { titleNode = element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); element.appendChild(titleNode); } titleNode.textContent = value; } // jQuery animate changes case if (key === 'strokeWidth') { key = 'stroke-width'; } // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke- // width is 0. #1369 if (key === 'stroke-width' || key === 'stroke') { wrapper[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (wrapper.stroke && wrapper['stroke-width']) { attr(element, 'stroke', wrapper.stroke); attr(element, 'stroke-width', wrapper['stroke-width']); wrapper.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) { element.removeAttribute('stroke'); wrapper.hasStroke = false; } skipAttr = true; } // symbols if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } // let the shadow follow the main element if (shadows && /^(width|height|visibility|x|y|d|transform)$/.test(key)) { i = shadows.length; while (i--) { attr( shadows[i], key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : value ); } } // validate heights if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) { value = 0; } // Record for animation and quick access without polling the DOM wrapper[key] = value; if (key === 'text') { // Delete bBox memo when the text changes if (value !== wrapper.textStr) { delete wrapper.bBox; } wrapper.textStr = value; if (wrapper.added) { renderer.buildText(wrapper); } } else if (!skipAttr) { attr(element, key, value); } } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (doTransform) { wrapper.updateTransform(); } } return ret; }, /** * Add a class name to an element */ addClass: function (className) { attr(this.element, 'class', attr(this.element, 'class') + ' ' + 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 (strokeWidth, x, y, width, height) { var wrapper = this, key, attribs = {}, values = {}, normalizer; strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges values.x = mathFloor(x || wrapper.x || 0) + normalizer; values.y = mathFloor(y || wrapper.y || 0) + normalizer; values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer); values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer); values.strokeWidth = strokeWidth; for (key in values) { if (wrapper[key] !== values[key]) { // only set attribute if changed wrapper[key] = attribs[key] = values[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { /*jslint unparam: true*//* allow unused param a in the regexp function below */ var elemWrapper = this, elem = elemWrapper.element, textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text', n, serializedCss = '', hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Merge the new styles with the old ones styles = extend( elemWrapper.styles, styles ); // store object elemWrapper.styles = styles; // Don't handle line wrap on canvas if (useCanVG && textWidth) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute if (textWidth) { delete styles.width; } css(elemWrapper.element, styles); } else { 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) { // touch if (hasTouch && eventType === 'click') { this.element.ontouchstart = function (e) { e.preventDefault(); handler(); }; } // simplest possible event model for internal use this.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; }, /** * 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(); } 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, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // 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; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * 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], nonLeft = align && align !== 'left', shadows = wrapper.shadows; // 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, height, rotation = wrapper.rotation, baseline, radians = 0, costheta = 1, sintheta = 0, quad, textWidth = pInt(wrapper.textWidth), xCorr = wrapper.xCorr || 0, yCorr = wrapper.yCorr || 0, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','), rotationStyle = {}, cssTransformKey; if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed if (defined(rotation)) { if (renderer.isSVG) { // #916 cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; } else { radians = rotation * deg2rad; // deg to rad costheta = mathCos(radians); sintheta = mathSin(radians); // 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://highcharts.com/tests/?file=text-rotation rotationStyle.filter = rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE; } css(elem, rotationStyle); } width = pick(wrapper.elemWidth, elem.offsetWidth); height = pick(wrapper.elemHeight, elem.offsetHeight); // update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } // correct x and y baseline = renderer.fontMetrics(elem.style.fontSize).b; xCorr = costheta < 0 && -width; yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(elem, { textAlign: align }); } // record correction wrapper.xCorr = xCorr; wrapper.yCorr = yCorr; } // apply position with correction css(elem, { left: (x + xCorr) + PX, top: (y + yCorr) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { height = elem.offsetHeight; // assigned to height for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * 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, 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 + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { attr(wrapper.element, '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 () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad; if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: 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 }; } 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) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') { 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)); } } wrapper.bBox = bBox; } return bBox; }, /** * Show the element */ show: function () { return this.attr({ visibility: 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.hide(); } }); }, /** * 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, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = this.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i, 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 the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks fireEvent(this, 'add'); 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, 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); }); } // 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; } }; /** * 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, forExport) { var renderer = this, loc = location, boxWrapper, desc; boxWrapper = renderer.createElement('svg') .attr({ xmlns: SVG_NS, version: '1.1' }); container.appendChild(boxWrapper.element); // object properties renderer.isSVG = true; renderer.box = boxWrapper.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.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); } }, /** * 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, lines = pick(wrapper.textStr, '').toString() .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), childNodes = textNode.childNodes, styleRegex = /style="([^"]+)"/, hrefRegex = /href="([^"]+)"/, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = textStyles && textStyles.width && pInt(textStyles.width), textLineHeight = textStyles && textStyles.lineHeight, i = childNodes.length; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } // 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 = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left attributes.x = parentX; } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // 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', textLineHeight || renderer.fontMetrics( /px$/.test(tspan.style.fontSize) ? tspan.style.fontSize : textStyles.fontSize ).h, // Safari 6.0.2 - too optimized for its own good (#1539) // TODO: revisit this with future versions of Safari isWebKit && tspan.offsetHeight ); } // Append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 tooLong, actualWidth, rest = []; while (words.length || rest.length) { delete wrapper.bBox; // delete cache actualWidth = wrapper.getBBox().width; tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: textLineHeight || 16, 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, '-'))); } } } } }); }); }, /** * 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) { var label = this.label(text, x, y, null, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, STYLE = 'style', 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]; // add the events addEvent(label.element, 'mouseenter', function () { label.attr(hoverState) .css(hoverStyle); }); addEvent(label.element, 'mouseleave', function () { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); }); label.setState = function (state) { curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } }; return label .on('click', function () { 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 }; return this.createElement('circle').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) { // arcs are defined as symbols for the ability to set // attributes in attr and animate if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } return this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); }, /** * 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').attr({ rx: r, ry: r, fill: NONE }); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * 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]; // 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 ]; } }, /** * 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; return wrapper; }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object. Prior to Highstock, an array was used to define * a linear gradient with pixel positions relative to the SVG. In newer versions * we change the coordinates to apply relative to the shape, using coordinates * 0-1 within the shape. To preserve backwards compatibility, linearGradient * in this definition is an object of x1, y1, x2 and y2. * * @param {Object} color The color or config object */ color: function (color, elem, prop) { var renderer = this, colorObject, regexRgba = /^rgba/, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color && color.linearGradient) { gradName = 'linearGradient'; } else if (color && 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].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 (regexRgba.test(stop[1])) { 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); }); } // Return the reference to the gradient object return 'url(' + renderer.url + '#' + id + ')'; // Webkit and Batik can't show rgba. } else if (regexRgba.test(color)) { colorObject = Color(color); attr(elem, prop + '-opacity', colorObject.get('a')); return colorObject.get('rgb'); } else { // Remove the opacity attribute added above. Does not throw if the attribute is not there. elem.removeAttribute(prop + '-opacity'); return color; } }, /** * 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, defaultChartStyle = defaultOptions.chart.style, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } x = mathRound(pick(x, 0)); y = mathRound(pick(y, 0)); wrapper = renderer.createElement('text') .attr({ x: x, y: y, text: str }) .css({ fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } wrapper.x = x; wrapper.y = y; return wrapper; }, /** * 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 defaultChartStyle = defaultOptions.chart.style, wrapper = this.createElement('span'), attrSetters = wrapper.attrSetters, element = wrapper.element, renderer = wrapper.renderer; // Text setter attrSetters.text = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = value; return false; }; // Various setters which rely on update transform attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); return false; }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // 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 = []; // 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.attrSetters, { translateX: function (value) { htmlGroupStyle.left = value + PX; }, translateY: function (value) { htmlGroupStyle.top = value + PX; }, visibility: 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; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize) { fontSize = pInt(fontSize || 11); // 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 + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline }; }, /** * 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, attrSetters = wrapper.attrSetters, 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) && text.getBBox(); 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).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) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(merge({ width: wrapper.width, height: 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) && (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, 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; } } function getSizeAfterAdd() { text.add(wrapper); wrapper.attr({ text: str, // alignment is available now x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ addEvent(wrapper, 'add', getSizeAfterAdd); /* * Add specific attribute setters. */ // only change local variables attrSetters.width = function (value) { width = value; return false; }; attrSetters.height = function (value) { height = value; return false; }; attrSetters.padding = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } return false; }; attrSetters.paddingLeft = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } return false; }; // change local variable and set attribue as well attrSetters.align = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; return false; // prevent setting text-anchor on the group }; // apply these to the box and the text alike attrSetters.text = function (value, key) { text.attr(key, value); updateBoxSize(); updateTextPadding(); return false; }; // apply these to the box but not to the text attrSetters[STROKE_WIDTH] = function (value, key) { needsBox = true; crispAdjust = value % 2 / 2; boxAttr(key, value); return false; }; attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) { if (key === 'fill') { needsBox = true; } boxAttr(key, value); return false; }; attrSetters.anchorX = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); return false; }; attrSetters.anchorY = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); return false; }; // rename attributes attrSetters.x = function (value) { wrapper.x = value; // for animation getter value -= alignFactor * ((width || bBox.width) + padding); wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); return false; }; attrSetters.y = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); return false; }; // 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(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration'], 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 () { removeEvent(wrapper, 'add', getSizeAfterAdd); // 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 = getSizeAfterAdd = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; /* **************************************************************************** * * * 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. */ Highcharts.VMLElement = 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; wrapper.attrSetters = {}; }, /** * 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 fireEvent(wrapper, 'add'); return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Get or set attributes */ attr: function (hash, val) { var wrapper = this, key, value, i, result, element = wrapper.element || {}, elemStyle = element.style, nodeName = element.nodeName, renderer = wrapper.renderer, symbolName = wrapper.symbolName, hasSetSymbolSize, shadows = wrapper.shadows, skipAttr, attrSetters = wrapper.attrSetters, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter, val is undefined if (isString(hash)) { key = hash; if (key === 'strokeWidth' || key === 'stroke-width') { ret = wrapper.strokeweight; } else { ret = wrapper[key]; } // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false && value !== null) { // #620 if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // prepare paths // symbols if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) { // 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 if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } else if (key === 'd') { value = value || []; wrapper.d = value.join(' '); // used in getter for animation // convert paths i = value.length; var convertedPath = [], clockwise; 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])) { convertedPath[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path convertedPath[i] = 'x'; } else { convertedPath[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 1 from the end X // position. #760, #1371. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { clockwise = value[i] === 'wa' ? 1 : -1; // #1642 if (convertedPath[i + 5] === convertedPath[i + 7]) { convertedPath[i + 7] -= clockwise; } // Start and end Y (#1410) if (convertedPath[i + 6] === convertedPath[i + 8]) { convertedPath[i + 8] -= clockwise; } } } } value = convertedPath.join(' ') || 'x'; element.path = value; // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } skipAttr = true; // handle visibility } else if (key === 'visibility') { // let the shadow follow the main element if (shadows) { i = shadows.length; while (i--) { shadows[i].style[key] = value; } } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (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) { elemStyle[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } elemStyle[key] = value; skipAttr = true; // directly mapped to css } else if (key === 'zIndex') { if (value) { elemStyle[key] = value; } skipAttr = true; // x, y, width, height } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) { wrapper[key] = value; // used in getter if (key === 'x' || key === 'y') { key = { x: 'left', y: 'top' }[key]; } else { value = mathMax(0, value); // don't set width or height below zero (#311) } // clipping rectangle special if (wrapper.updateClipping) { wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' wrapper.updateClipping(); } else { // normal elemStyle[key] = value; } skipAttr = true; // class name } else if (key === 'class' && nodeName === 'DIV') { // IE8 Standards mode has problems retrieving the className element.className = value; // stroke } else if (key === 'stroke') { value = renderer.color(value, element, key); key = 'strokecolor'; // stroke width } else if (key === 'stroke-width' || key === 'strokeWidth') { element.stroked = value ? true : false; key = 'strokeweight'; wrapper[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } // dashStyle } else if (key === 'dashstyle') { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; wrapper.dashstyle = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ skipAttr = true; // fill } else if (key === 'fill') { if (nodeName === 'SPAN') { // text color elemStyle.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE ? true : false; value = renderer.color(value, element, key, wrapper); key = 'fillcolor'; } // opacity: don't bother - animation is too slow and filters introduce artifacts } else if (key === 'opacity') { /*css(element, { opacity: value });*/ skipAttr = true; // rotation on VML elements } else if (nodeName === 'shape' && key === 'rotation') { wrapper[key] = value; // Correction for the 1x1 size of the shape container. Used in gauge needles. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; element.style.top = mathRound(mathCos(value * deg2rad)) + PX; // translation for animation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') { wrapper[key] = value; wrapper.updateTransform(); skipAttr = true; // text for rotated and non-rotated elements } else if (key === 'text') { this.bBox = null; element.innerHTML = value; skipAttr = true; } if (!skipAttr) { if (docMode8) { // IE8 setAttribute bug element[key] = value; } else { attr(element, key, value); } } } } } return ret; }, /** * 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; } }; VMLElement = extendClass(SVGElement, VMLElement); /** * 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) { var renderer = this, boxWrapper, box; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV); box = boxWrapper.element; box.style.position = RELATIVE; // for freeform drawing using renderer directly container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; 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 doc.createStyleSheet().cssText = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; } }, /** * 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: [], left: isObj ? x.x : x, top: isObj ? x.y : y, width: isObj ? x.width : width, height: isObj ? x.height : height, 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) { 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 addEvent(wrapper, 'add', 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) return circle.attr({ x: x, y: y, width: 2 * r, height: 2 * r }); }, /** * 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; }, /** * VML uses a shape for rect to overcome bugs and rotation problems */ rect: function (x, y, width, height, r, strokeWidth) { if (isObject(x)) { y = x.y; width = x.width; height = x.height; strokeWidth = x.strokeWidth; x = x.x; } var wrapper = this.symbol('rect'); wrapper.r = r; return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var parentStyle = parentNode.style; css(element, { flip: 'x', left: pInt(parentStyle.width) - 1, top: pInt(parentStyle.height) - 1, rotation: -90 }); }, /** * 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) { // 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 * * @param {Number} left Left position * @param {Number} top Top position * @param {Number} r Border radius * @param {Object} options Width and height */ rect: function (left, top, width, height, options) { var right = left + width, bottom = top + height, ret, r; // No radius, return the more lightweight square if (!defined(options) || !options.r) { ret = SVGRenderer.prototype.symbols.square.apply(0, arguments); // Has radius add arcs for the corners } else { r = mathMin(options.r, width, height); ret = [ M, left + r, top, L, right - r, top, 'wa', right - 2 * r, top, right, top + 2 * r, right - r, top, right, top + r, L, right, bottom - r, 'wa', right - 2 * r, bottom - 2 * r, right, bottom, right, bottom - r, right - r, bottom, L, left + r, bottom, 'wa', left, bottom - 2 * r, left + 2 * r, bottom, left + r, bottom, left, bottom - r, L, left, top + r, 'wa', left, top, left + 2 * r, top + 2 * r, left, top + r, left + r, top, 'x', 'e' ]; } return ret; } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } /* **************************************************************************** * * * 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, horiz = axis.horiz, categories = axis.categories, names = axis.series[0] && axis.series[0].names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.optionsMarginLeft || chart.plotWidth / 2)), // #1580 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names && 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 }; css = extend(css, labelOptions.style); // first call if (!defined(label)) { attr = { align: labelOptions.align }; if (isNumber(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } tick.label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(css) .add(axis.labelGroup) : null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.labelBBox, // assume getLabelSize has run at this point axis = this.axis, options = axis.options, labelOptions = options.labels, width = bBox.width, leftSide = width * { left: 0, center: 0.5, right: 1 }[labelOptions.align] - labelOptions.x; return [-leftSide, width - leftSide]; }, /** * 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 (index, xy) { var show = true, axis = this.axis, chart = axis.chart, isFirst = this.isFirst, isLast = this.isLast, x = xy.x, reversed = axis.reversed, tickPositions = axis.tickPositions; if (isFirst || isLast) { var sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], plotLeft = chart.plotLeft, plotRight = plotLeft + axis.len, neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]], neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (x + leftSide < plotLeft) { // Align it to plot left x = plotLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (x + rightSide > plotRight) { // Align it to plot right x = plotRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = x; } return show; }, /** * 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; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Vertically centered if (!defined(labelOptions.y)) { y += pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2; } // Correct for staggered labels if (staggerLines) { y += (index / (step || 1) % staggerLines) * 16; } return { x: x, y: 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 = 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) || (!horiz && y === axis.pos + axis.len)) ? -1 : 1, // #1480 staggerLines = axis.staggerLines; 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 ((tick.isFirst && !pick(options.showFirstLabel, 1)) || (tick.isLast && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) { show = false; } // 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 */ function PlotLineOrBand(axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } } 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, halfPointRange = (axis.pointRange || 0) / 2, 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 // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); 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(); }; } } 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) { plotLine.label = label = renderer.text( optionsLabel.text, 0, 0 ) .attr({ align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, zIndex: zIndex }) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], pick(path[6], path[1])]; ys = [path[2], path[5], pick(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 () { var plotLine = this, axis = plotLine.axis; // remove it from the lookup erase(axis.plotLinesAndBands, plotLine); destroyObjectProperties(plotLine, this.axis); } }; /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption, stacking) { 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; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; this.percent = stacking === 'percent'; // 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); }, /** * Sets the total of this stack. Should be called when a serie is hidden or shown * since that will affect the total of other stacks. */ setTotal: function (total) { this.total = total; this.cum = total; }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, // docs: added stackLabel.format option 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, 0, 0, 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(this.percent ? 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.attr({ visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }); } } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { 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: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, 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: 5, 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: '#4d759e', //font: defaultFont.replace('normal', 'bold') fontWeight: 'bold' } //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: { align: 'right', 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 numberFormat(this.total, -1); }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { align: 'right', x: -8, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { align: 'left', x: 8, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { align: 'center', x: 0, y: 14 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { align: 'center', x: 0, y: -5 // 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.xOrY = isXAxis ? 'x' : 'y'; axis.opposite = userOptions.opposite; // needed in setOptions axis.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.staggerLines = axis.horiz && options.labels.staggerLines; 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'; // 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; // Flag if percentage mode //axis.usePercentage = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0; // Major ticks axis.ticks = {}; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // 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._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, // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() chart.axes.push(axis); chart[isXAxis ? 'xAxis' : 'yAxis'].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.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053) userOptions ) ); }, /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions); this.destroy(); this._addedPlotLB = false; // #1611 this.init(chart, newOptions); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.xOrY + 'Axis'; // xAxis or yAxis // Remove associated series each(this.series, function (series) { series.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(); } }, /** * 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 = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (value >= 1000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1); } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart, stacks = axis.stacks, posStack = [], negStack = [], stacksTouched = axis._stacksTouched = axis._stacksTouched + 1, type, i; axis.hasVisibleSeries = false; // reset dataMin and dataMax in case we're redrawing axis.dataMin = axis.dataMax = null; // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, stacking, posPointStack, negPointStack, stackKey, stackOption, negKey, xData, yData, x, y, threshold = seriesOptions.threshold, yDataLength, activeYData = [], seriesDataMin, seriesDataMax, activeCounter = 0; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = seriesOptions.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 { var isNegative, pointStack, key, cropped = series.cropped, xExtremes = series.xAxis.getExtremes(), //findPointRange, //pointRange, j, hasModifyValue = !!series.modifyValue; // Handle stacking stacking = seriesOptions.stacking; axis.usePercentage = stacking === 'percent'; // create a stack for this particular series type if (stacking) { stackOption = seriesOptions.stack; stackKey = series.type + pick(stackOption, ''); negKey = '-' + stackKey; series.stackKey = stackKey; // used in translate posPointStack = posStack[stackKey] || []; // contains the total values for each x posStack[stackKey] = posPointStack; negPointStack = negStack[negKey] || []; negStack[negKey] = negPointStack; } if (axis.usePercentage) { axis.dataMin = 0; axis.dataMax = 99; } // processData can alter series.pointRange, so this goes after //findPointRange = series.pointRange === null; xData = series.processedXData; yData = series.processedYData; yDataLength = yData.length; // 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]; // 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) if (stacking) { isNegative = y < threshold; pointStack = isNegative ? negPointStack : posPointStack; key = isNegative ? negKey : stackKey; // Set the stack value and y for extremes if (defined(pointStack[x])) { // we're adding to the stack pointStack[x] = correctFloat(pointStack[x] + y); y = [y, pointStack[x]]; // consider both the actual value and the stack (#1376) } else { // it's the first point in the stack pointStack[x] = y; } // add the series if (!stacks[key]) { stacks[key] = {}; } // If the StackItem is there, just update the values, // if not, create one first if (!stacks[key][x]) { stacks[key][x] = new StackItem(axis, axis.options.stackLabels, isNegative, x, stackOption, stacking); } stacks[key][x].setTotal(pointStack[x]); stacks[key][x].touched = stacksTouched; } // Handle non null values if (y !== null && y !== UNDEFINED && (!axis.isLog || (y.length || y > 0))) { // general hook, used for Highstock compare values feature if (hasModifyValue) { y = series.modifyValue(y); } // For points within the visible range, including the first point outside the // visible range, consider y extremes if (series.getExtremesFromAll || cropped || ((xData[i + 1] || x) >= xExtremes.min && (xData[i - 1] || x) <= xExtremes.max)) { 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; } } } } // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If the length of activeYData is 0, continue with null values. if (!axis.usePercentage && activeYData.length) { series.dataMin = seriesDataMin = arrayMin(activeYData); series.dataMax = seriesDataMax = arrayMax(activeYData); 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; } } } } }); // Destroy unused stacks (#1044) for (type in stacks) { for (i in stacks[type]) { if (stacks[type][i].touched < stacksTouched) { stacks[type][i].destroy(); delete stacks[type][i]; } } } }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacementBetween) { var axis = this, axisLength = axis.len, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (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 = axisLength; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * axisLength; } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (pointPlacementBetween ? localA * axis.pointRange / 2 : 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) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, translatedValue = axis.translate(value, null, null, old), cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; 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; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0); }, /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, /** * 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 = []; // 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; }, /** * Set the tick positions of a logarithmic axis */ 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)) { // #1670 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, math.pow(10, mathFloor(math.log(interval) / math.LN10)) ); 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; }, /** * 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, len; 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( getTimeTicks( normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } 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 = 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, transA = axis.transA; // adjust translation for padding if (axis.isXAxis) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = series.pointRange, pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // 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, 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 */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, magnitude, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][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) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; if (secondPass) { 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.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; } } } // 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, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : (axis.max - axis.min) * tickPixelIntervalOption / (axis.len || 1) ); } // 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); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear magnitude = math.pow(10, mathFloor(math.log(axis.tickInterval) / math.LN10)); if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, magnitude, options); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { if (isDatetimeAxis) { tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)( normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (options.startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // 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 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = 0.001; // The lowest possible number to avoid extra padding on columns axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * 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) { axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // 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; } } // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * 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 // 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; // 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) { // Prevent pinch zooming out of range if (!this.allowZoomOutside) { if (newMin <= this.dataMin) { newMin = UNDEFINED; } if (newMax >= this.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, height, top, left; // Expose basic values to use in Series object and navigator this.left = left = pick(options.left, chart.plotLeft + offsetLeft); this.top = top = pick(options.top, chart.plotTop); this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight); this.height = height = pick(options.height, chart.plotHeight); 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); }, addPlotBand: function (options) { this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { 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 PlotLineOrBand(this, options).render(), userOptions = this.userOptions; // 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; }, /** * 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 axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n; // 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); // 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 }) .add(); } if (hasData || axis.isLinked) { each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); 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] === labelOptions.align) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset += (axis.staggerLines - 1) * 16; } } 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] }) .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); titleOffsetOption = axisTitleOptions.offset; } // 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.axisTitleMargin = pick(titleOffsetOption, labelOffset + titleMargin + (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x']) ); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], options.lineWidth); }, /** * 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; this.lineTop = lineTop; // used by flag series if (!opposite) { lineWidth *= -1; // crispify the other way - #1480 } 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, stacks = axis.stacks, 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; // 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.slice(1).concat([tickPositions[0]]), function (pos, i) { // Reorganize the indices i = (i === tickPositions.length - 1) ? 0 : i + 1; // 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); } ticks[pos].render(i, false, 1); } }); // 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) { 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 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) { var 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); } } } // End stacked totals axis.isDirty = false; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { var axis = this, chart = axis.chart, pointer = chart.pointer; // hide tooltip and hover states if (pointer.reset) { pointer.reset(true); } // render the axis axis.render(); // move plot lines and bands each(axis.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(axis.series, function (series) { series.isDirty = true; }); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); }, /** * Destroys an Axis instance. */ destroy: function () { var axis = this, stacks = axis.stacks, stackKey; // Remove the events 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, axis.plotLinesAndBands], function (coll) { destroyObjectProperties(coll); }); // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); } }; // end Axis /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ function Tooltip() { 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, 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) .hide() .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 () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.destroy(); } }); // 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; // get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: 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 && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) { // 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 () { 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(this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Hide the crosshairs */ hideCrosshairs: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.hide(); } }); }, /** * 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, plotX = 0, plotY = 0, yAxis; 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; plotX += point.plotX; 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) { // Set up the variables var chart = this.chart, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, distance = pick(this.options.distance, 12), pointX = point.plotX, pointY = point.plotY, x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance), y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip alignedRight; // It is too far to the left, adjust it if (x < 7) { x = plotLeft + mathMax(pointX, 0) + distance; } // Test to see if the tooltip is too far to the right, // if it is, move it back to be inside and then up to not cover the point. if ((x + boxWidth) > (plotLeft + plotWidth)) { x -= (x + boxWidth) - (plotLeft + plotWidth); y = pointY - boxHeight + plotTop - distance; alignedRight = true; } // If it is now above the plot area, align it to the top of the plot area if (y < plotTop + 5) { y = plotTop + 5; // If the tooltip is still covering the point, move it below instead if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) { y = pointY + plotTop + distance; // below } } // Now if the tooltip is below the chart, move it up. It's better to cover the // point than to disappear outside the chart. #834. if (y + boxHeight > plotTop + plotHeight) { y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below } return {x: x, y: y}; }, /** * 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), series = items[0].series, s; // build the header s = [series.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); 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, show, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, crosshairsOptions = options.crosshairs, 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; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; // For line type series, hide tooltip if the point falls outside the plot show = shared || !currentSeries.isCartesian || currentSeries.tooltipOutsidePlot || chart.isInsidePlot(x, y); // update the inner HTML if (text === false || !show) { 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 }); this.isHidden = false; } // crosshairs if (crosshairsOptions) { crosshairsOptions = splat(crosshairsOptions); // [x, y] var path, i = crosshairsOptions.length, attribs, axis, val; while (i--) { axis = point.series[i ? 'yAxis' : 'xAxis']; if (crosshairsOptions[i] && axis) { val = i ? pick(point.stackY, point.y) : point.x; // #814 if (axis.isLog) { // #1671 val = log2lin(val); } path = axis.getPlotLinePath( val, 1 ); if (tooltip.crosshairs[i]) { tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE }); } else { attribs = { 'stroke-width': crosshairsOptions[i].width || 1, stroke: crosshairsOptions[i].color || '#C0C0C0', zIndex: crosshairsOptions[i].zIndex || 2 }; if (crosshairsOptions[i].dashStyle) { attribs.dashstyle = crosshairsOptions[i].dashStyle; } tooltip.crosshairs[i] = chart.renderer.path(path) .attr(attribs) .add(); } } } } 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 ); } }; /** * 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 */ function Pointer(chart, options) { this.init(chart, options); } Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var zoomType = useCanVG ? '' : options.chart.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.pinchDown = []; this.lastValidTouch = {}; if (options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e) { var chartPosition, chartX, chartY, ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Framework specific normalizing (#1165) e = washMouseEvent(e); // iOS ePos = e.touches ? e.touches.item(0) : e; // get mouse position this.chartPosition = chartPosition = offset(this.chart.container); // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = e.x; 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; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * 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, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } }, /** * 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) { 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); // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); tooltip.hideCrosshairs(); } pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart; // Scale each series each(chart.series, function (series) { if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(attribs); if (series.markerGroup) { series.markerGroup.attr(attribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(attribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { 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 = 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 = 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, followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, zoomHor = self.zoomHor || self.pinchHor, zoomVert = self.zoomVert || self.pinchVert, hasZoom = zoomHor || zoomVert, selectionMarker = self.selectionMarker, transform = {}, clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if (e.type === 'touchstart') { if (followTouchMove || hasZoom) { 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(axis.dataMin), max = axis.toPixels(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); } }); // 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); } if (zoomHor) { self.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (zoomVert) { self.pinchTranslateDirection(false, 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 && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } } }, /** * 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; 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; // 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) { 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(chartX); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.x, selectionTop = selectionBox.y, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)), selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height)); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.xOrY + 'Axis'].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({ translateX: chart.plotLeft, translateY: chart.plotTop, scaleX: 1, scaleY: 1 }); } } // 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) { this.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, hoverSeries = chart.hoverSeries; // Get e.pageX and e.pageY back in MooTools e = washMouseEvent(e); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && hoverSeries.isCartesian && !chart.isInsidePlot(e.pageX - chartPosition.left - chart.plotLeft, e.pageY - chartPosition.top - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { this.reset(); this.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; // normalize e = this.normalize(e); // #295 e.returnValue = false; if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if (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; if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop, inverted = chart.inverted, chartPosition, plotX, plotY; 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')) { chartPosition = this.chartPosition; plotX = hoverPoint.plotX; plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: chartPosition.left + plotLeft + (inverted ? chart.plotWidth - plotY : plotX), pageY: chartPosition.top + plotTop + (inverted ? chart.plotHeight - plotX : plotY) }); // 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); } } } }, onContainerTouchStart: function (e) { var chart = this.chart; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Prevent the click pseudo event from firing unless it is set in the options /*if (!chart.runChartClick) { e.preventDefault(); }*/ // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } } 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) { this.drop(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, events; this._events = events = [ [container, 'onmousedown', 'onContainerMouseDown'], [container, 'onmousemove', 'onContainerMouseMove'], [container, 'onclick', 'onContainerClick'], [container, 'mouseleave', 'onContainerMouseLeave'], [doc, 'mousemove', 'onDocumentMouseMove'], [doc, 'mouseup', 'onDocumentMouseUp'] ]; if (hasTouch) { events.push( [container, 'ontouchstart', 'onContainerTouchStart'], [container, 'ontouchmove', 'onContainerTouchMove'], [doc, 'touchend', 'onDocumentTouchEnd'] ); } each(events, function (eventConfig) { // First, create the callback function that in turn calls the method on Pointer pointer['_' + eventConfig[2]] = function (e) { pointer[eventConfig[2]](e); }; // Now attach the function, either as a direct property or through addEvent if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]]; } else { addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var pointer = this; // Release all DOM events each(pointer._events, function (eventConfig) { if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE } else { removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); delete pointer._events; // memory and CPU leak clearInterval(pointer.tooltipTimeout); } }; /** * The overview of the chart's series */ function Legend(chart, options) { this.init(chart, options); } Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; 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.lastLineHeight = 0; // 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.color : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { stroke: symbolColor, 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) { 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].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; 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.legendItemWidth + 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; 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); } titleHeight = this.title.getBBox().height; 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 = options.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, 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, itemOptions = series.options, showCheckbox = itemOptions.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); // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); // 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, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? li : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); li.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { li.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); } }); // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (itemOptions && showCheckbox) { item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, options.itemCheckboxStyle, chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.legendItemWidth = options.itemWidth || symbolWidth + symbolPadding + bBox.width + padding + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = bBox.height; // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // 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 : itemWidth, legend.offsetWidth ); }, /** * 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 = []; each(chart.series, function (serie) { var seriesOptions = serie.options; if (!seriesOptions.showInLegend || defined(seriesOptions.linkedTo)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( serie.legendItems || (seriesOptions.legendType === 'point' ? serie.data : serie) ); }); // 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 each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; 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(null, null, null, legendWidth, 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, pageCount, 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; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight; this.pageCount = pageCount = mathCeil(legendHeight / clipHeight); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, 0, 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 pageCount = this.pageCount, 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 + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + this.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 = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1; this.scrollGroup.animate({ translateY: scrollOffset }); pager.attr({ text: currentPage + '/' + pageCount }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * 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 var optionsChart = options.chart, optionsMargin = optionsChart.margin, margin = isObject(optionsMargin) ? optionsMargin : [optionsMargin, optionsMargin, optionsMargin, optionsMargin]; this.optionsMarginTop = pick(optionsChart.marginTop, margin[0]); this.optionsMarginRight = pick(optionsChart.marginRight, margin[1]); this.optionsMarginBottom = pick(optionsChart.marginBottom, margin[2]); this.optionsMarginLeft = pick(optionsChart.marginLeft, margin[3]); 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); // 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 = 0; chart.counters = new ChartCounters(); 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; }, /** * 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 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 })); /*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); } }, /** * 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; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * 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, 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(); } // link stacked series while (i--) { serie = series[i]; if (serie.isDirty && serie.options.stacking) { hasStackedSeries = true; break; } } if (hasStackedSeries) { // 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; } if (chart.hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); chart.getMargins(); // 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', axis.getExtremes()); // #747, #751 }); } if (axis.isDirty || isDirtyBox || hasStackedSeries) { axis.redraw(); isDirtyBox = true; // #792 } }); } // 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) { 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(); }); }, /** * 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; var loadingOptions = options.loading; // 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 ); } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '', left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } }, /** * 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; }, /** * 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); }); chart.adjustTickAmounts(); }, /** * 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; }); }, /** * 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 (chartX) { var chart = this, xAxis = chart.xAxis[0], mouseDownX = chart.mouseDownX, halfPointRange = xAxis.pointRange / 2, extremes = xAxis.getExtremes(), newMin = xAxis.translate(mouseDownX - chartX, true) + halfPointRange, newMax = xAxis.translate(mouseDownX + chart.plotWidth - chartX, true) - halfPointRange, hoverPoints = chart.hoverPoints; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (xAxis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { xAxis.setExtremes(newMin, newMax, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions) { 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() .align(chartTitleOptions, false, 'spacingBox'); } }); }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) chart.containerWidth = adapterRun(renderTo, 'width'); chart.containerHeight = adapterRun(renderTo, 'height'); chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(optionsChart.height, // 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) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); 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 oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex]) { 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 if (!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; chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, true) : new Renderer(container, chartWidth, chartHeight); 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); } }, /** * 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 () { var chart = this, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, axisOffset, legend = chart.legend, optionsMarginTop = chart.optionsMarginTop, optionsMarginLeft = chart.optionsMarginLeft, optionsMarginRight = chart.optionsMarginRight, optionsMarginBottom = chart.optionsMarginBottom, chartTitleOptions = chart.options.title, chartSubtitleOptions = chart.options.subtitle, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 10), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // adjust for title and subtitle if ((chart.title || chart.subtitle) && !defined(chart.optionsMarginTop)) { titleOffset = mathMax( (chart.title && !chartTitleOptions.floating && !chartTitleOptions.verticalAlign && chartTitleOptions.y) || 0, (chart.subtitle && !chartSubtitleOptions.floating && !chartSubtitleOptions.verticalAlign && chartSubtitleOptions.y) || 0 ); if (titleOffset) { chart.plotTop = mathMax(chart.plotTop, titleOffset + pick(chartTitleOptions.margin, 15) + spacingTop); } } // adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(optionsMarginRight)) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacingRight ); } } else if (align === 'left') { if (!defined(optionsMarginLeft)) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacingLeft ); } } else if (verticalAlign === 'top') { if (!defined(optionsMarginTop)) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacingTop ); } } else if (verticalAlign === 'bottom') { if (!defined(optionsMarginBottom)) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacingBottom ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(optionsMarginLeft)) { chart.plotLeft += axisOffset[3]; } if (!defined(optionsMarginTop)) { chart.plotTop += axisOffset[0]; } if (!defined(optionsMarginBottom)) { chart.marginBottom += axisOffset[2]; } if (!defined(optionsMarginRight)) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Add the event handlers necessary for auto resizing * */ initReflow: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, reflowTimeout; function reflow(e) { var width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win; // #805 - MooTools doesn't supply e // 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(reflowTimeout); chart.reflowTimeout = reflowTimeout = setTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }, 100); } chart.containerWidth = width; chart.containerHeight = height; } } 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)); } css(chart.container, { width: chartWidth + PX, height: chartHeight + PX }); 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.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, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, 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 = plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacingLeft, y: spacingTop, width: chartWidth - spacingLeft - spacingRight, height: chartHeight - spacingTop - spacingBottom }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; 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: 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, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft; chart.plotTop = pick(chart.optionsMarginTop, spacingTop); chart.marginRight = pick(chart.optionsMarginRight, spacingRight); chart.marginBottom = pick(chart.optionsMarginBottom, spacingBottom); chart.plotLeft = pick(chart.optionsMarginLeft, spacingLeft); 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) .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp(null, null, null, chartWidth - mgn, 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, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight) ); } } // 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; }); }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; var labels = options.labels, credits = options.credits, creditsHref; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); 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(); } each(chart.series, function (serie) { serie.translate(); serie.setTooltipPoints(); serie.render(); }); // 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; renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; chart.credits = renderer.text( credits.text, 0, 0 ) .on('click', function () { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } // Set flag chart.hasRendered = true; }, /** * 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; 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); }); // 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 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) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * 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.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.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 = { y: options }; } else if (isArray(options)) { ret = {}; // 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 }; }, /** * 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; if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887 this.firePointEvent('mouseOut'); this.setState(); chart.hoverPoint = null; } }, /** * 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 }); }, /** * 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) { var point = this, series = point.series, graphic = point.graphic, i, data = series.data, chart = series.chart; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function () { point.applyOptions(options); // update visuals if (isObject(options)) { series.getAttribs(); if (graphic) { graphic.attr(point.pointAttr[series.state]); } } // record changes in the parallel arrays i = inArray(point, data); series.xData[i] = point.x; series.yData[i] = series.toYData ? series.toYData(point) : point.y; series.zData[i] = point.z; series.options.data[i] = point.options; // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(animation); } }); }, /** * 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) { var point = this, series = point.series, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); data.splice(i, 1); series.options.data.splice(i, 1); series.xData.splice(i, 1); series.yData.splice(i, 1); series.zData.splice(i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); }, /** * 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); }, /** * 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) { 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, newSymbol, pointAttr = point.pointAttr; state = state || NORMAL_STATE; // empty string if ( // already has this state state === point.state || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // point marker's state options is disabled (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr[state].r; point.graphic.attr(merge( pointAttr[state], radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); } 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) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr[state]) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; // Move the existing graphic } else { stateMarkerGraphic.attr({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide'](); } } point.state = state; } }; /** * @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 = 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' }, colorCounter: 0, init: function (chart, options) { var series = this, eventType, events, linkedTo, chartSeries = chart.series; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions // 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 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) stableSort(chartSeries, function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, a._i); }); each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); // Linked series linkedTo = options.linkedTo; series.linkedSeries = []; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chartSeries[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }, /** * 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; if (series.isCartesian) { each(['xAxis', 'yAxis'], 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]) { error(18, true); } }); } }, /** * 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 series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.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, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // the tooltip options are merged between global and series specific options this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip); // Delte marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, /** * Get the series' color */ getColor: function () { var options = this.options, userOptions = this.userOptions, defaultColors = this.chart.options.colors, counters = this.chart.counters, color, colorIndex; color = options.color || defaultPlotOptions[this.type].color; if (!color && !options.colorByPoint) { if (defined(userOptions._colorIndex)) { // after Series.update() colorIndex = userOptions._colorIndex; } else { userOptions._colorIndex = counters.color; colorIndex = counters.color++; } color = defaultColors[colorIndex]; } this.color = color; counters.wrapColor(defaultColors.length); }, /** * Get the series' symbol */ getSymbol: function () { var series = this, userOptions = series.userOptions, seriesMarkerOption = series.options.marker, chart = series.chart, defaultSymbols = chart.options.symbols, counters = chart.counters, symbolIndex; series.symbol = seriesMarkerOption.symbol; if (!series.symbol) { if (defined(userOptions._symbolIndex)) { // after Series.update() symbolIndex = userOptions._symbolIndex; } else { userOptions._symbolIndex = counters.symbol; symbolIndex = counters.symbol++; } series.symbol = defaultSymbols[symbolIndex]; } // don't substract radius in image symbols (#604) if (/^url/.test(series.symbol)) { seriesMarkerOption.radius = 0; } counters.wrapSymbol(defaultSymbols.length); }, /** * 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 */ drawLegendSymbol: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legendOptions.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, baseline = legend.baseline, 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, baseline - 4, L, symbolWidth, baseline - 4 ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, baseline - 4 - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); } }, /** * 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, xData = series.xData, yData = series.yData, zData = series.zData, names = series.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point; setAnimation(animation, chart); // Make graph animate sideways if (graph && shift) { graph.shift = currentShift + 1; } if (area) { if (shift) { // #780 area.shift = currentShift + 1; } 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]); xData.push(point.x); yData.push(series.toYData ? series.toYData(point) : point.y); zData.push(point.z); if (names) { names[point.x] = point.name; } dataOptions.push(options); // 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(); xData.shift(); yData.shift(); zData.shift(); dataOptions.shift(); } } series.getAttribs(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw) { var series = this, oldData = series.points, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, names = xAxis && xAxis.categories && !xAxis.categories.length ? [] : null, i; // reset properties series.xIncrement = null; series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // parallel arrays var xData = [], yData = [], zData = [], dataLength = data ? data.length : [], turboThreshold = options.turboThreshold || 1000, pt, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length, hasToYData = !!series.toYData; // 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 (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]]); xData[i] = pt.x; yData[i] = hasToYData ? series.toYData(pt) : pt.y; zData[i] = pt.z; if (names && pt.name) { names[i] = pt.name; } } } } // Unsorted data is not supported by the line tooltip as well as data grouping and // navigation in Stock charts (#725) if (series.requireSorting && xData.length > 1 && xData[1] < xData[0]) { error(15); } // 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.xData = xData; series.yData = yData; series.zData = zData; series.names = names; // destroy old points i = (oldData && oldData.length) || 0; 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; if (pick(redraw, true)) { chart.redraw(false); } }, /** * 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; if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * 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, cropStart = 0, cropEnd = dataLength, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian; // 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; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { var extremes = xAxis.getExtremes(), min = extremes.min, max = extremes.max; // 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) { // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (processedXData[i] >= min) { cropStart = mathMax(0, i - 1); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (processedXData[i] > max) { cropEnd = i + 1; break; } } processedXData = processedXData.slice(cropStart, cropEnd); processedYData = processedYData.slice(cropStart, cropEnd); 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; } } // 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; }, /** * 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]))); } } // 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; }, /** * 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, isBottomSeries, allStackSeries, i, placeBetween = options.pointPlacement === 'between', threshold = options.threshold; //nextSeriesDown; // Is it the last visible series? (#809, #1722). // TODO: After merging in the 'stacking' branch, this logic should probably be moved to Chart.getStacks allStackSeries = yAxis.series.sort(function (a, b) { return a.index - b.index; }); i = allStackSeries.length; while (i--) { if (allStackSeries[i].visible) { if (allStackSeries[i] === series) { // #809 isBottomSeries = true; } break; } } // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = yAxis.stacks[(yValue < threshold ? '-' : '') + series.stackKey], pointStack, pointStackTotal; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, placeBetween); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; pointStackTotal = pointStack.total; pointStack.cum = yBottom = pointStack.cum - yValue; // start from top yValue = yBottom + yValue; if (isBottomSeries) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } if (stacking === 'percent') { yBottom = pointStackTotal ? yBottom * 100 / pointStackTotal : 0; yValue = pointStackTotal ? yValue * 100 / pointStackTotal : 0; } point.percentage = pointStackTotal ? point.y * 100 / pointStackTotal : 0; point.total = point.stackTotal = pointStackTotal; point.stackY = yValue; } // 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 = (typeof yValue === 'number' && yValue !== Infinity) ? mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 UNDEFINED; // Set client related positions for mouse tracking point.clientX = placeBetween ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Memoize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; // Set this range's low to the last range's high plus one low = points[i - 1] ? high + 1 : 0; // Now find the new high high = points[i + 1] ? mathMax(0, mathFloor((point.clientX + (points[i + 1] ? points[i + 1].clientX : axisLength)) / 2)) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } series.tooltipPoints = tooltipPoints; }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = this, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime', headerFormat = tooltipOptions.headerFormat, closestPointRange = xAxis && xAxis.closestPointRange, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { if (closestPointRange) { for (n in timeUnits) { if (timeUnits[n] >= closestPointRange) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } } // Insert the header date format if any if (isDateTime && xDateFormat && isNumber(point.key)) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); }, /** * 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; }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = '_sharedClip' + animation.duration + animation.easing; // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(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 ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animation.duration); } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group; if (group && this.options.clip !== false) { group.clip(chart.clipRect); this.markerGroup.clip(); // no clip } // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } }, 100); }, /** * 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, pointMarkerOptions, enabled, isInside, markerGroup = series.markerGroup; if (seriesMarkerOptions.enabled || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = point.plotX; plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858 // 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]; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic .attr({ // Since the marker group isn't clipped, each individual marker must be toggled visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }) .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 ) .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, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, 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 + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } 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(); } // 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; while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } 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 pointStateOptionsHover.color = Color(pointStateOptionsHover.color || point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness).get(); } // normal point state inherits series wide normal state pointAttr[NORMAL_STATE] = series.convertAttribs(extend({ color: point.color // #868 }, 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] ); // Force the fill to negativeColor on markers if (point.negative && seriesOptions.marker && negativeColor) { pointAttr[NORMAL_STATE].fill = pointAttr[HOVER_STATE].fill = pointAttr[SELECT_STATE].fill = series.convertAttribs({ fillColor: negativeColor }).fill; } // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var 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; // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); extend(this, seriesTypes[newOptions.type || oldType].prototype); this.init(chart, newOptions); if (pick(redraw, true)) { chart.redraw(false); } }, /** * 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(['xAxis', 'yAxis'], 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]; } }, /** * Draw the data labels */ drawDataLabels: function () { var series = this, seriesOptions = series.options, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, str, dataLabelsGroup; 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', series.visible ? VISIBLE : HIDDEN, options.zIndex || 6 ); // 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; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = generalOptions.enabled || (pointOptions && pointOptions.enabled); // 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) { rotation = options.rotation; // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.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 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(options.style) .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 */ 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(), alignAttr; // the final position; // 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 alignAttr = { align: options.align, x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; } // Show or hide based on the final aligned position dataLabel.attr({ visibility: options.crop === false || /*chart.isInsidePlot(alignAttr.x, alignAttr.y) || */chart.isInsidePlot(plotX, plotY, inverted) ? (chart.renderer.isSVG ? 'inherit' : VISIBLE) : HIDDEN }); }, /** * 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]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // 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 && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } 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 */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor, translatedThreshold, posAttr, negAttr, graph = this.graph, area = this.area, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), above, below; if (negativeColor && (graph || area)) { translatedThreshold = mathCeil(this.yAxis.len - this.yAxis.translate(options.threshold || 0)); above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax - translatedThreshold }; if (chart.inverted && renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } if (this.yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.negClip = negClip = renderer.clipRect(negAttr); if (graph) { graph.clip(posClip); this.graphNeg.clip(negClip); } if (area) { area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * 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, chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Generate it on first call if (isNew) { this[prop] = group = 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']({ translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }); return group; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, doAnimation = animation && !!series.animate && chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE 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 (doAnimation) { 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.clipNeg(); } // draw the data labels (inn pies they go before the points) series.drawDataLabels(); // draw the points series.drawPoints(); // draw the mouse tracking area if (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 if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (doAnimation) { series.animate(); } else if (!hasRendered) { 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.setTooltipPoints(true); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } }, /** * 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 + 1; } 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) { 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'); }, /** * 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. */ drawTracker: 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(); } }; // 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 = tracker = renderer.path(trackerPath) .attr({ 'class': PREFIX + 'tracker', '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 }) .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css) .add(series.markerGroup); if (hasTouch) { tracker.on('touchstart', onMouseOver); } } } }; // end Series prototype /** * 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 segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, 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) { keys.push(+x); } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { // The point exists, push it to the segment 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 { plotX = xAxis.translate(x); plotY = yAxis.toPixels(stack[x].cum, 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; 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--) { // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, segment[i].yBottom); } areaSegmentPath.push(segment[i].plotX, segment[i].yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment); } 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) { var translatedThreshold = this.yAxis.getThreshold(this.options.threshold); 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, negativeColor = options.negativeColor, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color if (negativeColor) { props.push(['areaNeg', options.negativeColor, options.negativeFillColor]); } 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(options.fillOpacity || 0.75).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, legend.options.symbolWidth, 12, 2 ).attr({ zIndex: 3 }).add(item.legendGroup); } }); 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 }); 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 }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', tooltipOutsidePlot: true, requireSorting: false, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', r: 'borderRadius' }, trackerGroups: ['group', 'dataLabelsGroup'], /** * 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, chart = series.chart, options = series.options, xAxis = this.xAxis, 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(chart.series, function (otherSeries) { var otherOptions = otherSeries.options; if (otherSeries.type === series.type && otherSeries.visible && series.options.group === otherOptions.group) { // used in Stock charts navigator series 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 || 1), 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, stacking = options.stacking, borderWidth = options.borderWidth, yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width pointXOffset = metrics.offset; Series.prototype.translate.apply(series); // record the new values each(series.points, function (point) { var plotY = mathMin(mathMax(-999, point.plotY), yAxis.len + 999), // Don't draw too far outside plot area (#1303) yBottom = pick(point.yBottom, translatedThreshold), barX = point.plotX + pointXOffset, barY = mathCeil(mathMin(plotY, yBottom)), barH = mathCeil(mathMax(plotY, yBottom) - barY), stack = yAxis.stacks[(point.y < 0 ? '-' : '') + series.stackKey], shapeArgs; // Record the offset'ed position and width of the bar to be able to align the stacking total correctly if (stacking && series.visible && stack && stack[point.x]) { stack[point.x].setOffset(pointXOffset, barW); } // handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = 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) } } point.barX = barX; point.pointWidth = pointWidth; // create shape type and shape args that are reused in drawPoints and drawTracker point.shapeType = 'rect'; point.shapeArgs = shapeArgs = chart.renderer.Element.prototype.crisp.call(0, borderWidth, barX, barY, barW, barH); if (borderWidth % 2) { // correct for shorting in crisp method, visible in stacked columns with 1px border shapeArgs.y -= 1; shapeArgs.height += 1; } }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * 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, options = series.options, renderer = series.chart.renderer, shapeArgs; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic.animate(merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ drawTracker: function () { var series = this, pointer = series.chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; series.onMouseOver(); while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED) { // 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); } } }); } else { series._hasTracking = true; } }, /** * Override the basic data label alignment by adjusting for the position of the column */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), 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: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - 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); }, /** * 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, tooltip: { headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>', followPointer: true }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup'], drawTracker: ColumnSeries.prototype.drawTracker, setTooltipPoints: noop }); 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 () { return this.point.name; } // softConnector: true, //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; // Disallow negative values (#1530) if (point.y < 0) { point.y = null; } //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function () { point.slice(); }; 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, method; // 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 method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][method](); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { 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); } } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], 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) { Series.prototype.setData.call(this, data, false); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(); } }, /** * 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; return map(positions, function (length, i) { isPercent = /%$/.test(length); handleSlicingRoom = i < 2 || (i === 2 && isPercent); return (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length) + (handleSlicingRoom ? slicingRoom : 0); }); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var total = 0, series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngleRad = series.startAngleRad = mathPI / 180 * ((options.startAngle || 0) % 360 - 90), points = series.points, circ = 2 * mathPI, fraction, 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((y - positions[1]) / (positions[2] / 2 + labelDistance)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle fraction = total ? point.y / total : 0; start = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; if (!ignoreHiddenPoint || point.visible) { cumulative += fraction; } end = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: start, end: end }; // center for the sliced out slice angle = (end + start) / 2; if (angle > 0.75 * circ) { angle -= 2 * mathPI; } 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 < circ / 4 ? 0 : 1; 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 ]; // API properties point.percentage = fraction * 100; point.total = total; } this.setTooltipPoints(); }, 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.arc(shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility if (point.visible === false) { point.setVisible(false); } }); }, /** * Override the base drawDataLabels method by pie specific functionality */ 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; }, sortByAngle = function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }; // get out if not enabled if (!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) { // it may have been cancelled in the base method (#407) halves[point.half].push(point); } }); // assume equal label heights i = 0; while (!labelHeight && data[i]) { // #1569 labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968 i++; } /* 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, length = points.length, slotIndex; // Sort by angle sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // build the slots for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) { slots.push(pos); // visualize the slot /* var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver' }) .add(); chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4) .attr({ fill: 'silver' }).add(); } */ } slotsLength = slots.length; // 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 = naturalY; } } 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(slotIndex === 0 || slotIndex === slots.length - 1 ? 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 }) .add(series.group); } } else if (connector) { point.connector = connector.destroy(); } }); } } }, /** * 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. */ 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 } }); this.drawDataLabels(); // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }, /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ 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 }); } } }); }, alignDataLabel: noop, /** * Draw point specific tracker objects. Inherit directly from column series. */ drawTracker: ColumnSeries.prototype.drawTracker, /** * Use a simple symbol from column prototype */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Legend: Legend, Pointer: Pointer, Point: Point, Tick: Tick, Tooltip: Tooltip, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
assets/jqwidgets/demos/react/app/grid/roweditwitheverpresentrow/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { render() { let source = { localdata: generatedata(10), datafields: [ { name: 'name', type: 'string' }, { name: 'productname', type: 'string' }, { name: 'available', type: 'bool' }, { name: 'date', type: 'date' }, { name: 'quantity', type: 'number' } ], datatype: 'array' }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'Name', columntype: 'textbox', filtertype: 'input', datafield: 'name', width: 215 }, { text: 'Product', filtertype: 'checkedlist', datafield: 'productname', width: 220 }, { text: 'Ship Date', datafield: 'date', filtertype: 'range', width: 210, cellsalign: 'right', cellsformat: 'd' }, { text: 'Qty.', datafield: 'quantity', filtertype: 'number', cellsalign: 'right' } ]; return ( <JqxGrid width={850} source={dataAdapter} filterable={true} showeverpresentrow={true} everpresentrowposition={'top'} everpresentrowactions={'update reset'} columns={columns} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/layouts/Group/FactList.js
armaanshah96/lunchbox
import React from 'react' import PropTypes from 'prop-types' import {List, ListItem} from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; export const FactList = ({ children }) => ( <List> <Subheader>Fun Facts </Subheader> <ListItem primaryText="Fun Fact 1" secondaryText="I love llamas" /> <ListItem primaryText="Fun Fact 2" secondaryText="Dragons and React" /> <ListItem primaryText="Fun Fact 1" secondaryText="I love llamas" /> <ListItem primaryText="Fun Fact 2" secondaryText="Dragons and React" /> <ListItem primaryText="Fun Fact 1" secondaryText="I love llamas" /> <ListItem primaryText="Fun Fact 2" secondaryText="Dragons and React" /> </List> ) FactList.propTypes = { children: PropTypes.node, } export default FactList
gatsby-site/src/pages/work.js
serendipitist/serendipitist
import React from 'react' import Link from 'gatsby-link' const SecondPage = () => ( <div> <h3> I like working on Front end technologies. Currently working for digital publishing platform Startup in Bangalore.</h3> <h3>When I get some time I like building stuff and improve my tech skills </h3> </div> ) export default SecondPage
src/index.js
DaveOrDead/react-dnd-character-generator
/* eslint-disable import/default */ import React from 'react'; import {render} from 'react-dom'; import {Provider} from 'react-redux'; import {Router, browserHistory} from 'react-router'; import routes from './routes'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/styles.scss'; const store = configureStore(); render( <Provider store={store}> <Router history={browserHistory} routes={routes} /> </Provider>, document.getElementById('app') );
src/svg-icons/image/hdr-off.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageHdrOff = (props) => ( <SvgIcon {...props}> <path d="M17.5 15v-2h1.1l.9 2H21l-.9-2.1c.5-.2.9-.8.9-1.4v-1c0-.8-.7-1.5-1.5-1.5H16v4.9l1.1 1.1h.4zm0-4.5h2v1h-2v-1zm-4.5 0v.4l1.5 1.5v-1.9c0-.8-.7-1.5-1.5-1.5h-1.9l1.5 1.5h.4zm-3.5-1l-7-7-1.1 1L6.9 9h-.4v2h-2V9H3v6h1.5v-2.5h2V15H8v-4.9l1.5 1.5V15h3.4l7.6 7.6 1.1-1.1-12.1-12z"/> </SvgIcon> ); ImageHdrOff = pure(ImageHdrOff); ImageHdrOff.displayName = 'ImageHdrOff'; ImageHdrOff.muiName = 'SvgIcon'; export default ImageHdrOff;
ajax/libs/react-table/5.4.0/react-table.js
holtkamp/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.reactTable = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _objectWithoutProperties(e,t){var o={};for(var a in e)t.indexOf(a)>=0||Object.prototype.hasOwnProperty.call(e,a)&&(o[a]=e[a]);return o}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(e[a]=o[a])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames),_utils=require("./utils"),_utils2=_interopRequireDefault(_utils),_pagination=require("./pagination"),_pagination2=_interopRequireDefault(_pagination),emptyObj=function(){return{}};exports.default={data:[],loading:!1,showPagination:!0,showPageSizeOptions:!0,pageSizeOptions:[5,10,20,25,50,100],defaultPageSize:20,showPageJump:!0,expanderColumnWidth:35,collapseOnSortingChange:!0,collapseOnPageChange:!0,collapseOnDataChange:!0,freezeWhenExpanded:!1,defaultSorting:[],showFilters:!1,defaultFiltering:[],defaultFilterMethod:function(e,t,o){var a=e.pivotId||e.id;return void 0===t[a]||String(t[a]).startsWith(e.value)},onExpandSubComponent:void 0,onPageChange:void 0,onPageSizeChange:void 0,onSortingChange:void 0,onFilteringChange:void 0,pivotBy:void 0,pivotColumnWidth:200,pivotValKey:"_pivotVal",pivotIDKey:"_pivotID",subRowsKey:"_subRows",onExpandRow:void 0,onChange:function(){return null},className:"",style:{},getProps:emptyObj,getTableProps:emptyObj,getTheadGroupProps:emptyObj,getTheadGroupTrProps:emptyObj,getTheadGroupThProps:emptyObj,getTheadProps:emptyObj,getTheadTrProps:emptyObj,getTheadThProps:emptyObj,getTheadFilterProps:emptyObj,getTheadFilterTrProps:emptyObj,getTheadFilterThProps:emptyObj,getTbodyProps:emptyObj,getTrGroupProps:emptyObj,getTrProps:emptyObj,getTdProps:emptyObj,getTfootProps:emptyObj,getTfootTrProps:emptyObj,getTfootTdProps:emptyObj,getPaginationProps:emptyObj,getLoadingProps:emptyObj,getNoDataProps:emptyObj,column:{sortable:!0,show:!0,minWidth:100,render:void 0,className:"",style:{},getProps:emptyObj,header:void 0,headerClassName:"",headerStyle:{},getHeaderProps:emptyObj,footer:void 0,footerClassName:"",footerStyle:{},getFooterProps:emptyObj,filterMethod:void 0,hideFilter:!1},previousText:"Previous",nextText:"Next",loadingText:"Loading...",noDataText:"No rows found",pageText:"Page",ofText:"of",rowsText:"rows",TableComponent:_utils2.default.makeTemplateComponent("rt-table"),TheadComponent:_utils2.default.makeTemplateComponent("rt-thead"),TbodyComponent:_utils2.default.makeTemplateComponent("rt-tbody"),TrGroupComponent:_utils2.default.makeTemplateComponent("rt-tr-group"),TrComponent:_utils2.default.makeTemplateComponent("rt-tr"),ThComponent:function(e){var t=e.toggleSort,o=e.className,a=e.children,n=_objectWithoutProperties(e,["toggleSort","className","children"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)(o,"rt-th"),onClick:function(e){t&&t(e)}},n),a)},TdComponent:_utils2.default.makeTemplateComponent("rt-td"),TfootComponent:_utils2.default.makeTemplateComponent("rt-tfoot"),ExpanderComponent:function(e){var t=e.isExpanded,o=_objectWithoutProperties(e,["isExpanded"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)("rt-expander",t&&"-open")},o),"•")},PaginationComponent:_pagination2.default,PreviousComponent:void 0,NextComponent:void 0,LoadingComponent:function(e){var t=e.className,o=e.loading,a=e.loadingText,n=_objectWithoutProperties(e,["className","loading","loadingText"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)("-loading",{"-active":o},t)},n),_react2.default.createElement("div",{className:"-loading-inner"},a))},NoDataComponent:_utils2.default.makeTemplateComponent("rt-noData")}; },{"./pagination":5,"./utils":6,"classnames":7,"react":"react"}],2:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactTableDefaults=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(e[s]=a[s])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames),_utils=require("./utils"),_utils2=_interopRequireDefault(_utils),_lifecycle=require("./lifecycle"),_lifecycle2=_interopRequireDefault(_lifecycle),_methods=require("./methods"),_methods2=_interopRequireDefault(_methods),_defaultProps=require("./defaultProps"),_defaultProps2=_interopRequireDefault(_defaultProps),ReactTableDefaults=exports.ReactTableDefaults=_defaultProps2.default;exports.default=_react2.default.createClass(_extends({displayName:"src"},_lifecycle2.default,_methods2.default,{render:function(){var e=this,t=this.getResolvedState(),a=t.children,s=t.className,l=t.style,n=t.getProps,d=t.getTableProps,r=t.getTheadGroupProps,i=t.getTheadGroupTrProps,o=t.getTheadGroupThProps,u=t.getTheadProps,c=t.getTheadTrProps,f=t.getTheadThProps,m=t.getTheadFilterProps,p=t.getTheadFilterTrProps,_=t.getTheadFilterThProps,h=t.getTbodyProps,x=t.getTrGroupProps,v=t.getTrProps,y=t.getTdProps,g=t.getTfootProps,P=t.getTfootTrProps,w=t.getTfootTdProps,N=t.getPaginationProps,E=t.getLoadingProps,C=t.getNoDataProps,T=t.showPagination,W=t.expanderColumnWidth,R=t.manual,D=t.loadingText,b=t.noDataText,k=t.showFilters,F=t.loading,q=t.pageSize,S=t.page,z=t.sorting,G=t.filtering,V=t.pages,M=t.pivotValKey,j=t.subRowsKey,H=t.expandedRows,I=t.onExpandRow,K=t.TableComponent,O=t.TheadComponent,L=t.TbodyComponent,A=t.TrGroupComponent,B=t.TrComponent,J=t.ThComponent,Q=t.TdComponent,U=t.TfootComponent,X=t.ExpanderComponent,Y=t.PaginationComponent,Z=t.LoadingComponent,$=t.SubComponent,ee=t.NoDataComponent,te=t.resolvedData,ae=t.allVisibleColumns,se=t.headerGroups,le=t.hasHeaderGroups,ne=t.sortedData,de=q*S,re=de+q,ie=R?te:ne.slice(de,re),oe=this.getMinRows(),ue=_utils2.default.range(Math.max(oe-ie.length,0)),ce=ae.some(function(e){return e.footer}),fe=function e(t){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;return t.forEach(function(t,l){s++,t._viewIndex=s;var n=a.concat([l]);t[j]&&_utils2.default.get(H,n)&&(s=e(t[j],n,s))}),s};fe(ie);var me=S>0,pe=S+1<V,_e=_utils2.default.sum(ae.map(function(e){return _utils2.default.getFirstDefined(e.width,e.minWidth)})),he=-1,xe=_extends({},t,{startRow:de,endRow:re,pageRows:ie,minRows:oe,padRows:ue,hasColumnFooter:ce,canPrevious:me,canNext:pe,rowMinWidth:_e}),ve=function(){var t=_utils2.default.splitProps(r(xe,void 0,void 0,e)),a=_utils2.default.splitProps(i(xe,void 0,void 0,e));return _react2.default.createElement(O,_extends({className:(0,_classnames2.default)("-headerGroups",t.className),style:_extends({},t.style,{minWidth:_e+"px"})},t.rest),_react2.default.createElement(B,_extends({className:a.className,style:a.style},a.rest),se.map(ye)))},ye=function(t,a){var s=_utils2.default.sum(t.columns.map(function(e){return e.width?0:e.minWidth})),l=_utils2.default.sum(t.columns.map(function(e){return _utils2.default.getFirstDefined(e.width,e.minWidth)})),n=_utils2.default.sum(t.columns.map(function(e){return _utils2.default.getFirstDefined(e.width,e.maxWidth)})),d=_utils2.default.splitProps(o(xe,void 0,t,e)),r=_utils2.default.splitProps(t.getHeaderProps(xe,void 0,t,e)),i=[t.headerClassName,d.className,r.className],u=_extends({},t.headerStyle,d.style,r.style),c=_extends({},d.rest,r.rest),f={flex:s+" 0 auto",width:l+"px",maxWidth:n+"px"};return t.expander?t.pivotColumns?_react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)("rt-pivot-header",i),style:_extends({},u,f)},c)):_react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)("rt-expander-header",i),style:_extends({},u,{flex:"0 0 auto",width:W+"px"})},c)):_react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)(i),style:_extends({},u,f)},c),_utils2.default.normalizeComponent(t.header,{data:ne,column:t}))},ge=function(){var t=_utils2.default.splitProps(u(xe,void 0,void 0,e)),a=_utils2.default.splitProps(c(xe,void 0,void 0,e));return _react2.default.createElement(O,_extends({className:(0,_classnames2.default)("-header",t.className),style:_extends({},t.style,{minWidth:_e+"px"})},t.rest),_react2.default.createElement(B,_extends({className:a.className,style:a.style},a.rest),ae.map(Pe)))},Pe=function(t,a){var s=z.find(function(e){return e.id===t.id}),l="function"==typeof t.show?t.show():t.show,n=_utils2.default.getFirstDefined(t.width,t.minWidth),d=_utils2.default.getFirstDefined(t.width,t.maxWidth),r=_utils2.default.splitProps(f(xe,void 0,t,e)),i=_utils2.default.splitProps(t.getHeaderProps(xe,void 0,t,e)),o=[t.headerClassName,r.className,i.className],u=_extends({},t.headerStyle,r.style,i.style),c=_extends({},r.rest,i.rest);if(t.expander){if(t.pivotColumns){var m=z.find(function(e){return e.id===t.id});return _react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)("rt-pivot-header",t.sortable&&"-cursor-pointer",o,m?m.desc?"-sort-desc":"-sort-asc":""),style:_extends({},u,{flex:n+" 0 auto",width:n+"px",maxWidth:d+"px"}),toggleSort:function(a){t.sortable&&e.sortColumn(t.pivotColumns,a.shiftKey)}},c),t.pivotColumns.map(function(e,a){return _react2.default.createElement("span",{key:e.id},_utils2.default.normalizeComponent(e.header,{data:ne,column:t}),a<t.pivotColumns.length-1&&_react2.default.createElement(X,null))}))}return _react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)("rt-expander-header",o),style:_extends({},u,{flex:"0 0 auto",width:W+"px"})},c))}return _react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)(o,s?s.desc?"-sort-desc":"-sort-asc":"",t.sortable&&"-cursor-pointer",!l&&"-hidden"),style:_extends({},u,{flex:n+" 0 auto",width:n+"px",maxWidth:d+"px"}),toggleSort:function(a){t.sortable&&e.sortColumn(t,a.shiftKey)}},c),_utils2.default.normalizeComponent(t.header,{data:ne,column:t}))},we=function(){var t=_utils2.default.splitProps(m(xe,void 0,void 0,e)),a=_utils2.default.splitProps(p(xe,void 0,void 0,e));return _react2.default.createElement(O,_extends({className:(0,_classnames2.default)("-filters",t.className),style:_extends({},t.style,{minWidth:_e+"px"})},t.rest),_react2.default.createElement(B,_extends({className:a.className,style:a.style},a.rest),ae.map(Ne)))},Ne=function(t,a){var s=_utils2.default.getFirstDefined(t.width,t.minWidth),l=_utils2.default.getFirstDefined(t.width,t.maxWidth),n=_utils2.default.splitProps(_(xe,void 0,t,e)),d=_utils2.default.splitProps(t.getHeaderProps(xe,void 0,t,e)),r=[t.headerClassName,n.className,d.className],i=_extends({},t.headerStyle,n.style,d.style),o=_extends({},n.rest,d.rest);if(t.expander){if(t.pivotColumns){for(var u=[],c=function(a){var s=t.pivotColumns[a],l=G.find(function(e){return e.id===t.id&&e.pivotId===s.id});u.push(_react2.default.createElement("span",{key:s.id,style:{display:"flex",alignContent:"flex-end",flex:1}},s.hideFilter?null:_react2.default.createElement("input",{type:"text",style:{flex:1,width:20},value:l?l.value:"",onChange:function(a){return e.filterColumn(t,a,s)}}))),a<t.pivotColumns.length-1&&u.push(_react2.default.createElement(X,{key:s.id+"-"+a}))},f=0;f<t.pivotColumns.length;f++)c(f);return _react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)("rt-pivot-header",t.sortable&&"-cursor-pointer",r),style:_extends({},i,{flex:s+" 0 auto",width:s+"px",maxWidth:l+"px",display:"flex"})},o),u)}return _react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)("rt-expander-header",r),style:_extends({},i,{flex:"0 0 auto",width:W+"px"})},o))}var m=G.find(function(e){return e.id===t.id});return _react2.default.createElement(J,_extends({key:a,className:(0,_classnames2.default)(r),style:_extends({},i,{flex:s+" 0 auto",width:s+"px",maxWidth:l+"px"})},o),t.hideFilter?null:_react2.default.createElement("input",{type:"text",style:{width:"100%"},value:m?m.value:"",onChange:function(a){return e.filterColumn(t,a)}}))},Ee=function t(a,s){var l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n={row:a.__original,rowValues:a,index:a.__index,viewIndex:++he,level:l.length,nestingPath:l.concat([s]),aggregated:!!a[j],subRows:a[j]},d=_utils2.default.get(H,n.nestingPath),r=x(xe,n,void 0,e),i=_utils2.default.splitProps(v(xe,n,void 0,e));return _react2.default.createElement(A,_extends({key:n.nestingPath.join("_")},r),_react2.default.createElement(B,_extends({className:(0,_classnames2.default)(i.className,a._viewIndex%2?"-even":"-odd"),style:i.style},i.rest),ae.map(function(t,s){var l="function"==typeof t.show?t.show():t.show,r=_utils2.default.getFirstDefined(t.width,t.minWidth),i=_utils2.default.getFirstDefined(t.width,t.maxWidth),o=_utils2.default.splitProps(y(xe,n,t,e)),u=_utils2.default.splitProps(t.getProps(xe,n,t,e)),c=[o.className,t.className,u.className],f=_extends({},o.style,t.style,u.style);if(t.expander){var m=function(t){if(I)return I(n.nestingPath,t);var a=_utils2.default.clone(H);return d?e.setStateWithData({expandedRows:_utils2.default.set(a,n.nestingPath,!1)}):e.setStateWithData({expandedRows:_utils2.default.set(a,n.nestingPath,{})})};if(t.pivotColumns){var p=t.pivotRender;return _react2.default.createElement(Q,_extends({key:s,className:(0,_classnames2.default)("rt-pivot",c),style:_extends({},f,{paddingLeft:1===n.nestingPath.length?void 0:30*(n.nestingPath.length-1)+"px",flex:r+" 0 auto",width:r+"px",maxWidth:i+"px"})},o.rest,{onClick:m}),n.subRows?_react2.default.createElement("span",null,_react2.default.createElement(X,{isExpanded:d}),t&&t.pivotRender?_react2.default.createElement(p,_extends({},n,{value:n.rowValues[M]})):_react2.default.createElement("span",null,a[M]," (",n.subRows.length,")")):$?_react2.default.createElement("span",null,_react2.default.createElement(X,{isExpanded:d})):null)}return _react2.default.createElement(Q,{key:s,className:(0,_classnames2.default)(c,{hidden:!l}),style:_extends({},f,{flex:"0 0 auto",width:W+"px"}),onClick:m},_react2.default.createElement("span",null,_react2.default.createElement(X,{isExpanded:d})))}return _react2.default.createElement(Q,_extends({key:s,className:(0,_classnames2.default)(c,!l&&"hidden"),style:_extends({},f,{flex:r+" 0 auto",width:r+"px",maxWidth:i+"px"})},o.rest),_utils2.default.normalizeComponent(t.render,_extends({},n,{value:n.rowValues[t.id]}),n.rowValues[t.id]))})),n.subRows&&d&&n.subRows.map(function(e,a){return t(e,a,n.nestingPath)}),$&&!n.subRows&&d&&$(n))},Ce=function(t,a){var s=x(xe,void 0,void 0,e),l=_utils2.default.splitProps(v(xe,void 0,void 0,e));return _react2.default.createElement(A,_extends({key:a},s),_react2.default.createElement(B,{className:(0,_classnames2.default)("-padRow",l.className),style:l.style||{}},ae.map(function(t,a){var s="function"==typeof t.show?t.show():t.show,l=_utils2.default.getFirstDefined(t.width,t.minWidth),n=_utils2.default.getFirstDefined(t.width,t.maxWidth),d=_utils2.default.splitProps(y(xe,void 0,t,e)),r=_utils2.default.splitProps(t.getProps(xe,void 0,t,e)),i=[d.className,t.className,r.className],o=_extends({},d.style,t.style,r.style);return _react2.default.createElement(Q,_extends({key:a,className:(0,_classnames2.default)(i,!s&&"hidden"),style:_extends({},o,{flex:l+" 0 auto",width:l+"px",maxWidth:n+"px"})},d.rest)," ")})))},Te=function(){var t=g(xe,void 0,void 0,e),a=_utils2.default.splitProps(P(xe,void 0,void 0,e));return _react2.default.createElement(U,_extends({className:t.className,style:_extends({},t.style,{minWidth:_e+"px"})},t.rest),_react2.default.createElement(B,_extends({className:(0,_classnames2.default)(a.className),style:a.style},a.rest),ae.map(function(t,a){var s="function"==typeof t.show?t.show():t.show,l=_utils2.default.getFirstDefined(t.width,t.minWidth),n=_utils2.default.getFirstDefined(t.width,t.maxWidth),d=_utils2.default.splitProps(w(xe,void 0,void 0,e)),r=_utils2.default.splitProps(t.getProps(xe,void 0,t,e)),i=_utils2.default.splitProps(t.getFooterProps(xe,void 0,t,e)),o=[d.className,t.className,r.className,i.className],u=_extends({},d.style,t.style,r.style,i.style);return t.expander?t.pivotColumns?_react2.default.createElement(Q,_extends({key:a,className:(0,_classnames2.default)("rt-pivot",o),style:_extends({},u,{flex:l+" 0 auto",width:l+"px",maxWidth:n+"px"})},r.rest,d.rest,i.rest),_utils2.default.normalizeComponent(t.footer)):_react2.default.createElement(Q,{key:a,className:(0,_classnames2.default)(o,{hidden:!s}),style:_extends({},u,{flex:"0 0 auto",width:W+"px"})}):_react2.default.createElement(Q,_extends({key:a,className:(0,_classnames2.default)(o,!s&&"hidden"),style:_extends({},u,{flex:l+" 0 auto",width:l+"px",maxWidth:n+"px"})},r.rest,d.rest,i.rest),_utils2.default.normalizeComponent(t.footer,{data:ne,column:t}))})))},We=_utils2.default.splitProps(n(xe,void 0,void 0,this)),Re=_utils2.default.splitProps(d(xe,void 0,void 0,this)),De=_utils2.default.splitProps(h(xe,void 0,void 0,this)),be=_utils2.default.splitProps(N(xe,void 0,void 0,this)),ke=E(xe,void 0,void 0,this),Fe=C(xe,void 0,void 0,this),qe=function(){return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)("ReactTable",s,We.className),style:_extends({},l,We.style)},We.rest),_react2.default.createElement(K,_extends({className:(0,_classnames2.default)(Re.className),style:Re.style},Re.rest),le?ve():null,ge(),k?we():null,_react2.default.createElement(L,_extends({className:(0,_classnames2.default)(De.className),style:_extends({},De.style,{minWidth:_e+"px"})},De.rest),ie.map(function(e,t){return Ee(e,t)}),ue.map(Ce)),ce?Te():null),T?_react2.default.createElement(Y,_extends({},t,{pages:V,canPrevious:me,canNext:pe,onPageChange:e.onPageChange,onPageSizeChange:e.onPageSizeChange,className:be.className,style:be.style},be.rest)):null,!ie.length&&_react2.default.createElement(ee,Fe,_utils2.default.normalizeComponent(b)),_react2.default.createElement(Z,_extends({loading:F,loadingText:D},ke)))};return a?a(xe,qe,this):qe()}})); },{"./defaultProps":1,"./lifecycle":3,"./methods":4,"./utils":6,"classnames":7,"react":"react"}],3:[function(require,module,exports){ "use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},_utils=require("./utils"),_utils2=_interopRequireDefault(_utils),_defaultProps=require("./defaultProps"),_defaultProps2=_interopRequireDefault(_defaultProps);exports.default={getDefaultProps:function(){return _defaultProps2.default},getInitialState:function(){return{page:0,pageSize:this.props.defaultPageSize||10,sorting:this.props.defaultSorting,expandedRows:{},filtering:this.props.defaultFiltering}},getResolvedState:function(t,e){var i=_extends({},_utils2.default.compactObject(this.state),_utils2.default.compactObject(e),_utils2.default.compactObject(this.props),_utils2.default.compactObject(t));return i},componentWillMount:function(){this.setStateWithData(this.getDataModel(this.getResolvedState()))},componentDidMount:function(){this.fireOnChange()},componentWillReceiveProps:function(t,e){var i=this.getResolvedState(),s=this.getResolvedState(t,e);i.defaultSorting!==s.defaultSorting&&(s.sorting=s.defaultSorting),i.showFilters===s.showFilters&&i.showFilters===s.showFilters||(s.filtering=s.defaultFiltering),i.data===s.data&&i.columns===s.columns&&i.pivotBy===s.pivotBy&&i.sorting===s.sorting&&i.showFilters===s.showFilters&&i.filtering===s.filtering||this.setStateWithData(this.getDataModel(s))},setStateWithData:function(t,e){var i=this.getResolvedState(),s=this.getResolvedState({},t),a=s.freezeWhenExpanded;if(s.frozen=!1,a)for(var r=Object.keys(s.expandedRows),o=0;o<r.length;o++)if(s.expandedRows[r[o]]){s.frozen=!0;break}return(i.frozen&&!s.frozen||i.sorting!==s.sorting||i.filtering!==s.filtering||i.showFilters!==s.showFilters||!s.frozen&&i.resolvedData!==s.resolvedData)&&((i.sorting!==s.sorting&&this.props.collapseOnSortingChange||i.filtering!==s.filtering||i.showFilters!==s.showFilters||!s.frozen&&i.resolvedData!==s.resolvedData&&this.props.collapseOnDataChange)&&(s.expandedRows={}),Object.assign(s,this.getSortedData(s))),s.sortedData&&(s.pages=s.manual?s.pages:Math.ceil(s.sortedData.length/s.pageSize)),this.setState(s,e)}}; },{"./defaultProps":1,"./utils":6}],4:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var _typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Object.defineProperty(exports,"__esModule",{value:!0});var _slicedToArray=function(){function e(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var u,a=e[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{!r&&a.return&&a.return()}finally{if(i)throw o}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":_typeof2(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":"undefined"==typeof e?"undefined":_typeof2(e)},_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},_utils=require("./utils"),_utils2=_interopRequireDefault(_utils);exports.default={getDataModel:function(e){var t=this,n=e.columns,r=e.pivotBy,i=void 0===r?[]:r,o=e.data,u=e.pivotIDKey,a=e.pivotValKey,s=e.subRowsKey,f=e.expanderColumnWidth,l=e.SubComponent,d=e.page,c=e.pages,p=e.pageSize,h=!1;n.forEach(function(e){e.columns&&(h=!0)});var g=[],v=[],y=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e[0];g.push(_extends({},t.props.column,n,{columns:e})),v=[]},m=n.map(function(e){return _extends({},e,{columns:e.columns?e.columns.filter(function(e){return!e.expander}):void 0})}),_=n.findIndex(function(e){return e.expander}),b=(l||i.length)&&_===-1,S=b?[{expander:!0}].concat(_toConsumableArray(m)):m;b&&(_=0);var x=function(e){var n=_extends({},t.props.column,e);if(n.expander)return n.width=f,n;if("string"==typeof n.accessor){var r=function(){n.id=n.id||n.accessor;var e=n.accessor;return n.accessor=function(t){return _utils2.default.get(t,e)},{v:n}}();if("object"===("undefined"==typeof r?"undefined":_typeof(r)))return r.v}if(n.accessor&&!n.id)throw console.warn(n),new Error("A column id is required if using a non-string accessor for column above.");return n.accessor||(n.accessor=function(e){}),n.maxWidth<n.minWidth&&(n.minWidth=n.maxWidth),n},C=function(e){var t=x(e);return D.push(t),t},D=[],w=S.map(function(e,t){return e.columns?_extends({},e,{columns:e.columns.map(C)}):C(e)}),O=w.slice(),P=[];if(O=O.map(function(e,t){if(e.columns){var n=e.columns.filter(function(e){return!(i.indexOf(e.id)>-1)&&_utils2.default.getFirstDefined(e.show,!0)});return _extends({},e,{columns:n})}return e}),O=O.filter(function(e){return e.columns?e.columns.length:!(i.indexOf(e.id)>-1)&&_utils2.default.getFirstDefined(e.show,!0)}),i.length){for(var R=[],A=0;A<D.length;A++)i.indexOf(D[A].id)>-1&&R.push(D[A]);var K=_extends({},R[0],{pivotColumns:R,expander:!0});O[_]=K}O.forEach(function(e,t){return e.columns?(P=P.concat(e.columns),v.length>0&&y(v),void y(e.columns,e)):(P.push(e),void v.push(e))}),h&&v.length>0&&y(v);var I=o.map(function(e,t){var n={__original:e,__index:t};return D.forEach(function(t){t.expander||(n[t.id]=t.accessor(e))}),n}),F=function(e){var t={};return W.forEach(function(n){var r=e.map(function(e){return e[n.id]});t[n.id]=n.aggregate(r,e)}),t},M=i.length?P.slice(1):P,W=M.filter(function(e){return e.aggregate}),E=void 0;i.length&&!function(){E=P[0];var e=function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(r===n.length)return t;var i=Object.entries(_utils2.default.groupBy(t,n[r])).map(function(e){var t,i=_slicedToArray(e,2),o=i[0],f=i[1];return t={},_defineProperty(t,u,n[r]),_defineProperty(t,a,o),_defineProperty(t,n[r],o),_defineProperty(t,s,f),t});return i=i.map(function(t){var i=e(t[s],n,r+1);return _extends({},t,_defineProperty({},s,i),F(i))})};I=e(I,i)}();var j=_utils2.default.getFirstDefined(c,Math.ceil(I.length/p)),z=d>j?z-1:d;return _extends({},e,{resolvedData:I,pivotColumn:E,allVisibleColumns:P,headerGroups:g,allDecoratedColumns:D,hasHeaderGroups:h,page:Math.max(z,0)})},getSortedData:function(e){var t=e.manual,n=e.sorting,r=e.filtering,i=e.showFilters,o=e.defaultFilterMethod,u=e.resolvedData,a=e.allVisibleColumns;return{sortedData:t?u:this.sortData(this.filterData(u,i,r,o,a),n)}},fireOnChange:function(){this.props.onChange(this.getResolvedState(),this)},getPropOrState:function(e){return _utils2.default.getFirstDefined(this.props[e],this.state[e])},getStateOrProp:function(e){return _utils2.default.getFirstDefined(this.state[e],this.props[e])},filterData:function(e,t,n,r,i){var o=this,u=e;return t&&n.length&&(u=n.reduce(function(e,t){return e.filter(function(e){var n=void 0;if(t.pivotId){var o=i.find(function(e){return e.id===t.id});n=o.pivotColumns.find(function(e){return e.id===t.pivotId})}else n=i.find(function(e){return e.id===t.id});var u=n.filterMethod||r;return u(t,e,n)})},u),u=u.map(function(e){return e[o.props.subRowsKey]?_extends({},e,_defineProperty({},o.props.subRowsKey,o.filterData(e[o.props.subRowsKey],t,n,r,i))):e}).filter(function(e){return!e[o.props.subRowsKey]||e[o.props.subRowsKey].length>0})),u},sortData:function(e,t){var n=this;if(!t.length)return e;var r=_utils2.default.orderBy(e,t.map(function(e){return function(t){return null===t[e.id]||void 0===t[e.id]?-(1/0):"string"==typeof t[e.id]?t[e.id].toLowerCase():t[e.id]}}),t.map(function(e){return!e.desc}));return r.map(function(e){return e[n.props.subRowsKey]?_extends({},e,_defineProperty({},n.props.subRowsKey,n.sortData(e[n.props.subRowsKey],t))):e})},getMinRows:function(){return _utils2.default.getFirstDefined(this.props.minRows,this.getStateOrProp("pageSize"))},onPageChange:function e(t){var n=this,r=this.props,e=r.onPageChange,i=r.collapseOnPageChange;if(e)return e(t);var o={page:t};i&&(o.expandedRows={}),this.setStateWithData(o,function(){n.fireOnChange()})},onPageSizeChange:function e(t){var n=this,e=this.props.onPageSizeChange,r=this.getResolvedState(),i=r.pageSize,o=r.page,u=i*o,a=Math.floor(u/t);return e?e(t,a):void this.setStateWithData({pageSize:t,page:a},function(){n.fireOnChange()})},sortColumn:function(e,t){var n=this,r=this.getResolvedState(),i=r.sorting,o=this.props.onSortingChange;if(o)return o(e,t);var u=_utils2.default.clone(i||[]).map(function(e){return e.desc=_utils2.default.isSortingDesc(e),e});if(_utils2.default.isArray(e))!function(){var n=u.findIndex(function(t){return t.id===e[0].id});if(n>-1){var r=u[n];r.desc?t?u.splice(n,e.length):e.forEach(function(e,t){u[n+t].desc=!1}):e.forEach(function(e,t){u[n+t].desc=!0}),t||(u=u.slice(n,e.length))}else u=t?u.concat(e.map(function(e){return{id:e.id,desc:!1}})):e.map(function(e){return{id:e.id,desc:!1}})}();else{var a=u.findIndex(function(t){return t.id===e.id});if(a>-1){var s=u[a];s.desc?t?u.splice(a,1):(s.desc=!1,u=[s]):(s.desc=!0,t||(u=[s]))}else t?u.push({id:e.id,desc:!1}):u=[{id:e.id,desc:!1}]}this.setStateWithData({page:!i.length&&u.length||!t?0:this.state.page,sorting:u},function(){n.fireOnChange()})},filterColumn:function(e,t,n){var r=this,i=this.getResolvedState(),o=i.filtering,u=this.props.onFilteringChange;if(u)return u(e,t);var a=(o||[]).filter(function(t){return t.id!==e.id||(t.pivotId?!n||t.pivotId!==n.id:void 0)});""!==t.target.value&&a.push({id:e.id,value:t.target.value,pivotId:n?n.id:void 0}),this.setStateWithData({page:0,filtering:a},function(){r.fireOnChange()})}}; },{"./utils":6}],5:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames),defaultButton=function(e){return _react2.default.createElement("button",_extends({type:"button"},e,{className:"-btn"}),e.children)};exports.default=_react2.default.createClass({displayName:"pagination",getInitialState:function(){return{page:this.props.page}},componentWillReceiveProps:function(e){this.setState({page:e.page})},getSafePage:function(e){return Math.min(Math.max(e,0),this.props.pages-1)},changePage:function(e){e=this.getSafePage(e),this.setState({page:e}),this.props.onPageChange(e)},applyPage:function(e){e&&e.preventDefault();var t=this.state.page;this.changePage(""===t?this.props.page:t)},render:function(){var e=this,t=this.props,a=t.pages,n=t.page,s=t.showPageSizeOptions,r=t.pageSizeOptions,c=t.pageSize,i=t.showPageJump,l=t.canPrevious,p=t.canNext,o=t.onPageSizeChange,u=t.className,g=t.PreviousComponent,f=void 0===g?defaultButton:g,d=t.NextComponent,m=void 0===d?defaultButton:d;return _react2.default.createElement("div",{className:(0,_classnames2.default)(u,"-pagination"),style:this.props.paginationStyle},_react2.default.createElement("div",{className:"-previous"},_react2.default.createElement(f,{onClick:function(t){l&&e.changePage(n-1)},disabled:!l},this.props.previousText)),_react2.default.createElement("div",{className:"-center"},_react2.default.createElement("span",{className:"-pageInfo"},this.props.pageText," ",i?_react2.default.createElement("div",{className:"-pageJump"},_react2.default.createElement("input",{type:""===this.state.page?"text":"number",onChange:function(t){var a=t.target.value,n=a-1;return""===a?e.setState({page:a}):void e.setState({page:e.getSafePage(n)})},value:""===this.state.page?"":this.state.page+1,onBlur:this.applyPage,onKeyPress:function(t){13!==t.which&&13!==t.keyCode||e.applyPage()}})):_react2.default.createElement("span",{className:"-currentPage"},n+1)," ",this.props.ofText," ",_react2.default.createElement("span",{className:"-totalPages"},a)),s&&_react2.default.createElement("span",{className:"select-wrap -pageSizeOptions"},_react2.default.createElement("select",{onChange:function(e){return o(Number(e.target.value))},value:c},r.map(function(t,a){return _react2.default.createElement("option",{key:a,value:t},t," ",e.props.rowsText)})))),_react2.default.createElement("div",{className:"-next"},_react2.default.createElement(m,{onClick:function(t){p&&e.changePage(n+1)},disabled:!p},this.props.nextText)))}}); },{"classnames":7,"react":"react"}],6:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _objectWithoutProperties(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function get(e,t,r){if(!t)return e;var n=makePathArray(t),o=void 0;try{o=n.reduce(function(e,t){return e[t]},e)}catch(e){}return"undefined"!=typeof o?o:r}function set(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],r=arguments[2],n=makePathArray(t),o=void 0,a=e;(o=n.shift())&&n.length;)a[o]||(a[o]={}),a=a[o];return a[o]=r,e}function takeRight(e,t){var r=t>e.length?0:e.length-t;return e.slice(r)}function last(e){return e[e.length-1]}function range(e){for(var t=[],r=0;r<e;r++)t.push(e);return t}function orderBy(e,t,r){return e.sort(function(e,n){for(var o=0;o<t.length;o++){var a=t[o],i=a(e),u=a(n),c=r[o]===!1||"desc"===r[o];if(i>u)return c?-1:1;if(i<u)return c?1:-1}return r[0]?e.__index-n.__index:n.__index-n.__index})}function remove(e,t){return e.filter(function(r,n){var o=t(r);return!!o&&(e.splice(n,1),!0)})}function clone(e){try{return JSON.parse(JSON.stringify(e,function(e,t){return"function"==typeof t?t.toString():t}))}catch(t){return e}}function getFirstDefined(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n=0;n<t.length;n++)if("undefined"!=typeof t[n])return t[n]}function sum(e){return e.reduce(function(e,t){return e+t},0)}function makeTemplateComponent(e){return function(t){var r=t.children,n=t.className,o=_objectWithoutProperties(t,["children","className"]);return _react2.default.createElement("div",_extends({className:(0,_classnames2.default)(e,n)},o),r)}}function groupBy(e,t){return e.reduce(function(e,r,n){var o="function"==typeof t?t(r,n):r[t];return e[o]=isArray(e[o])?e[o]:[],e[o].push(r),e},{})}function isArray(e){return Array.isArray(e)}function makePathArray(e){return flattenDeep(e).join(".").replace("[",".").replace("]","").split(".")}function flattenDeep(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(isArray(e))for(var r=0;r<e.length;r++)flattenDeep(e[r],t);else t.push(e);return t}function splitProps(e){var t=e.className,r=e.style,n=_objectWithoutProperties(e,["className","style"]);return{className:t,style:r,rest:n}}function compactObject(e){var t={};for(var r in e)e.hasOwnProperty(r)&&void 0!==e[r]&&"undefined"!=typeof e[r]&&(t[r]=e[r]);return t}function isSortingDesc(e){return!("desc"!==e.sort&&e.desc!==!0&&e.asc!==!1)}function normalizeComponent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e;return"function"==typeof e?Object.getPrototypeOf(e).isReactComponent?_react2.default.createElement(e,t):e(t):r}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames);exports.default={get:get,set:set,takeRight:takeRight,last:last,orderBy:orderBy,range:range,remove:remove,clone:clone,getFirstDefined:getFirstDefined,sum:sum,makeTemplateComponent:makeTemplateComponent,groupBy:groupBy,isArray:isArray,splitProps:splitProps,compactObject:compactObject,isSortingDesc:isSortingDesc,normalizeComponent:normalizeComponent}; },{"classnames":7,"react":"react"}],7:[function(require,module,exports){ !function(){"use strict";function e(){for(var r=[],o=0;o<arguments.length;o++){var f=arguments[o];if(f){var i=typeof f;if("string"===i||"number"===i)r.push(f);else if(Array.isArray(f))r.push(e.apply(null,f));else if("object"===i)for(var t in f)n.call(f,t)&&f[t]&&r.push(t)}}return r.join(" ")}var n={}.hasOwnProperty;"undefined"!=typeof module&&module.exports?module.exports=e:"function"==typeof define&&"object"==typeof define.amd&&define.amd?define("classnames",[],function(){return e}):window.classNames=e}(); },{}]},{},[2])(2) });
ajax/libs/react-native-web/0.12.0/exports/YellowBox/index.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import React from 'react'; import UnimplementedView from '../../modules/UnimplementedView'; var YellowBox = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(YellowBox, _React$Component); function YellowBox() { return _React$Component.apply(this, arguments) || this; } YellowBox.ignoreWarnings = function ignoreWarnings() {}; var _proto = YellowBox.prototype; _proto.render = function render() { return React.createElement(UnimplementedView, this.props); }; return YellowBox; }(React.Component); export default YellowBox;
test/client/app/components/survey_form_spec.js
inouetakuya/survey-builder
/** @jsx React.DOM */ var React = require("react/addons"); var TestUtils = React.addons.TestUtils; var SurveyForm = require('../../../../client/app/components/survey_form'); describe("components/survey_form", function (){ var subject, onChangeSpy; beforeEach(function () { onChangeSpy = jasmine.createSpy(); subject = TestUtils.renderIntoDocument( <SurveyForm title='Superhero survey' introduction='help us find out who is most awesome' onChange={onChangeSpy} /> ); }); describe('#render', function () { it('renders the title input', function () { var titleInput = TestUtils.findRenderedDOMComponentWithClass( subject, 'title' ); expect( titleInput).not.toBe( null ); }); it('renders the introduction textarea', function () { var introductionTextarea = TestUtils.findRenderedDOMComponentWithClass( subject, 'introduction' ); expect( introductionTextarea).not.toBe( null ); }); }); describe('#handleTitleChange', function () { it('calls the onChange prop', function () { subject.handleTitleChange({ target: { value: 'new title' }}); expect( onChangeSpy ).toHaveBeenCalledWith({ title: 'new title' }); }); }); describe('#handleIntroductionChange', function () { it('calls the onChange prop', function () { subject.handleIntroductionChange({ target: { value: 'new intro' }}); expect( onChangeSpy ).toHaveBeenCalledWith({ introduction: 'new intro' }); }); }); });
examples/auth-with-shared-root/components/App.js
tylermcginnis/react-router
import React from 'react' import { Link } from 'react-router' import auth from '../utils/auth' const App = React.createClass({ getInitialState() { return { loggedIn: auth.loggedIn() } }, updateAuth(loggedIn) { this.setState({ loggedIn: !!loggedIn }) }, componentWillMount() { auth.onChange = this.updateAuth auth.login() }, render() { return ( <div> <ul> <li> {this.state.loggedIn ? ( <Link to="/logout">Log out</Link> ) : ( <Link to="/login">Sign in</Link> )} </li> <li><Link to="/about">About</Link></li> <li><Link to="/">Home</Link> (changes depending on auth status)</li> <li><Link to="/page2">Page Two</Link> (authenticated)</li> <li><Link to="/user/foo">User: Foo</Link> (authenticated)</li> </ul> {this.props.children} </div> ) } }) module.exports = App
ajax/libs/rxjs/2.3.11/rx.compat.js
artch/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); 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) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @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 (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver() { __super__.apply(this, arguments); } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @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 TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ 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(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * 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)); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(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; }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
fields/types/money/MoneyField.js
tony2cssc/keystone
import Field from '../Field'; import React from 'react'; import { FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'MoneyField', valueChanged (event) { var newValue = event.target.value.replace(/[^\d\s\,\.\$€£¥]/g, ''); if (newValue === this.props.value) return; this.props.onChange({ path: this.props.path, value: newValue, }); }, renderField () { return <FormInput name={this.props.path} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" />; }, });
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js
powerreviews/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react' import tiniestCat from './assets/tiniest-cat.jpg' export default () => ( <img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" /> )