target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
docs/src/pages/getting-started/templates/checkout/Checkout.js
kybarg/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import CssBaseline from '@material-ui/core/CssBaseline'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Paper from '@material-ui/core/Paper'; import Stepper from '@material-ui/core/Stepper'; import Step from '@material-ui/core/Step'; import StepLabel from '@material-ui/core/StepLabel'; import Button from '@material-ui/core/Button'; import Link from '@material-ui/core/Link'; import Typography from '@material-ui/core/Typography'; import AddressForm from './AddressForm'; import PaymentForm from './PaymentForm'; import Review from './Review'; function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link color="inherit" href="https://material-ui.com/"> Your Website </Link>{' '} {new Date().getFullYear()} {'.'} </Typography> ); } const useStyles = makeStyles(theme => ({ appBar: { position: 'relative', }, layout: { width: 'auto', marginLeft: theme.spacing(2), marginRight: theme.spacing(2), [theme.breakpoints.up(600 + theme.spacing(2) * 2)]: { width: 600, marginLeft: 'auto', marginRight: 'auto', }, }, paper: { marginTop: theme.spacing(3), marginBottom: theme.spacing(3), padding: theme.spacing(2), [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: { marginTop: theme.spacing(6), marginBottom: theme.spacing(6), padding: theme.spacing(3), }, }, stepper: { padding: theme.spacing(3, 0, 5), }, buttons: { display: 'flex', justifyContent: 'flex-end', }, button: { marginTop: theme.spacing(3), marginLeft: theme.spacing(1), }, })); const steps = ['Shipping address', 'Payment details', 'Review your order']; function getStepContent(step) { switch (step) { case 0: return <AddressForm />; case 1: return <PaymentForm />; case 2: return <Review />; default: throw new Error('Unknown step'); } } export default function Checkout() { const classes = useStyles(); const [activeStep, setActiveStep] = React.useState(0); const handleNext = () => { setActiveStep(activeStep + 1); }; const handleBack = () => { setActiveStep(activeStep - 1); }; return ( <React.Fragment> <CssBaseline /> <AppBar position="absolute" color="default" className={classes.appBar}> <Toolbar> <Typography variant="h6" color="inherit" noWrap> Company name </Typography> </Toolbar> </AppBar> <main className={classes.layout}> <Paper className={classes.paper}> <Typography component="h1" variant="h4" align="center"> Checkout </Typography> <Stepper activeStep={activeStep} className={classes.stepper}> {steps.map(label => ( <Step key={label}> <StepLabel>{label}</StepLabel> </Step> ))} </Stepper> <React.Fragment> {activeStep === steps.length ? ( <React.Fragment> <Typography variant="h5" gutterBottom> Thank you for your order. </Typography> <Typography variant="subtitle1"> Your order number is #2001539. We have emailed your order confirmation, and will send you an update when your order has shipped. </Typography> </React.Fragment> ) : ( <React.Fragment> {getStepContent(activeStep)} <div className={classes.buttons}> {activeStep !== 0 && ( <Button onClick={handleBack} className={classes.button}> Back </Button> )} <Button variant="contained" color="primary" onClick={handleNext} className={classes.button} > {activeStep === steps.length - 1 ? 'Place order' : 'Next'} </Button> </div> </React.Fragment> )} </React.Fragment> </Paper> <Copyright /> </main> </React.Fragment> ); }
src/controls/FontFamily/__test__/fontFamilyControlTest.js
michalko/draft-wyswig
/* @flow */ import React from 'react'; import { expect, assert } from 'chai'; import { mount } from 'enzyme'; import { EditorState, convertFromHTML, ContentState, } from 'draft-js'; import FontFamilyControl from '..'; import { Dropdown } from '../../../components/Dropdown'; import defaultToolbar from '../../../config/defaultToolbar'; import ModalHandler from '../../../event-handler/modals'; import localeTranslations from '../../../i18n'; describe('FontFamilyControl test suite', () => { const contentBlocks = convertFromHTML('<div>test</div>'); const contentState = ContentState.createFromBlockArray(contentBlocks); const editorState = EditorState.createWithContent(contentState); it('should have a div when rendered', () => { expect(mount( <FontFamilyControl onChange={() => {}} editorState={editorState} config={defaultToolbar.fontFamily} modalHandler={new ModalHandler()} translations={localeTranslations.en} />, ).html().startsWith('<div')).to.equal(true); }); it('should have a dropdown child component well defined', () => { const control = mount( <FontFamilyControl onChange={() => {}} editorState={editorState} config={defaultToolbar.fontFamily} modalHandler={new ModalHandler()} translations={localeTranslations.en} />, ); assert.equal(control.childAt(0).props().children.length, 2); assert.isDefined(control.childAt(0).props().onChange); assert.equal(control.childAt(0).type(), Dropdown); }); });
node_modules/react-bootstrap/lib/factories/DropdownButton.js
mingnanwu/Angel-Hack-2015-EventRest
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _DropdownButton = require('../DropdownButton'); var _DropdownButton2 = _interopRequireDefault(_DropdownButton); exports['default'] = _react2['default'].createFactory(_DropdownButton2['default']); module.exports = exports['default'];
test/components/Counter.spec.js
miccferr/converterio
/* eslint no-unused-expressions: 0 */ import { expect } from 'chai'; import { spy } from 'sinon'; import React from 'react'; import { renderIntoDocument, scryRenderedDOMComponentsWithTag, findRenderedDOMComponentWithClass, Simulate } from 'react-addons-test-utils'; import Counter from '../../app/components/Counter'; function setup() { const actions = { increment: spy(), incrementIfOdd: spy(), incrementAsync: spy(), decrement: spy() }; const component = renderIntoDocument(<Counter counter={1} {...actions} />); return { component, actions, buttons: scryRenderedDOMComponentsWithTag(component, 'button').map(button => { return button; }), p: findRenderedDOMComponentWithClass(component, 'counter') }; } describe('Counter component', () => { it('should display count', () => { const { p } = setup(); expect(p.textContent).to.match(/^1$/); }); it('first button should call increment', () => { const { buttons, actions } = setup(); Simulate.click(buttons[0]); expect(actions.increment.called).to.be.true; }); it('second button should call decrement', () => { const { buttons, actions } = setup(); Simulate.click(buttons[1]); expect(actions.decrement.called).to.be.true; }); it('third button should call incrementIfOdd', () => { const { buttons, actions } = setup(); Simulate.click(buttons[2]); expect(actions.incrementIfOdd.called).to.be.true; }); it('fourth button should call incrementAsync', () => { const { buttons, actions } = setup(); Simulate.click(buttons[3]); expect(actions.incrementAsync.called).to.be.true; }); });
src/Containers/FlightMap/FlightMap.js
rahulp959/airstats.web
import React from 'react' import {fetchLiveFlights} from '../../ducks/liveflights.js' import {connect} from 'react-redux' import {withRouter} from 'react-router' import './FlightMap.scss' import {Map, Marker, Popup, TileLayer} from 'react-leaflet' import {DivIcon} from 'leaflet' import planeUrl from '../Flight/plane.png' let flightDispatcher class FlightMap extends React.Component { componentDidMount () { this.props.dispatch(fetchLiveFlights()) flightDispatcher = setInterval(() => this.props.dispatch(fetchLiveFlights()), 60000) } componentWillUnmount () { clearInterval(flightDispatcher) } flightTrack (id) { this.props.history.push(`/flight/${id}`) } renderMap () { const map = ( <Map center={[0, 0]} maxZoom={11} zoom={2}> <TileLayer url='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}' attribution='Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' /> <TileLayer url='https://stamen-tiles-{s}.a.ssl.fastly.net/toner-hybrid/{z}/{x}/{y}.png' attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' /> {this.renderPositions()} </Map> ) return map } renderPositions () { return this.props.flightPositions.map( (position) => { let divIcon = new DivIcon({ html: `<img src=${planeUrl} class=rotate-${position && position.get('hdg')} />`, iconSize: [32, 32] }) console.log(position.get('callsign')) return ( <Marker opacity={1} position={[parseFloat(position.get('lat')), parseFloat(position.get('lon'))]} icon={divIcon} key={`${position.get('callsign')}`}> <Popup> <div> <span className='row1'>ID: {position.get('callsign')}</span><br /> <span className='row2'>ALT: {position.get('alt')}</span><br /> <span className='row3'>RTE: {position.get('dep')}-{position.get('arr')}</span><br /> <span className='row4'>GS: {position.get('spd')}</span><br /><br /> <a onClick={() => { this.flightTrack(position.get('id')) }} className='track'>Flight Track</a> </div> </Popup> </Marker> ) } ) } render () { return ( <div className='mapbox'>{this.renderMap()}</div> ) } } const mapStateToProps = state => { return { flightPositions: state.getIn(['liveflights', 'flights']) } } export default withRouter(connect(mapStateToProps)(FlightMap))
packages/mui-icons-material/lib/TextFieldsOutlined.js
oliviertassinari/material-ui
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M2.5 4v3h5v12h3V7h5V4h-13zm19 5h-9v3h3v7h3v-7h3V9z" }), 'TextFieldsOutlined'); exports.default = _default;
src/decorators/withViewport.js
Gabs00/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); } }; } export default withViewport;
src/svg-icons/image/timer-off.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimerOff = (props) => ( <SvgIcon {...props}> <path d="M19.04 4.55l-1.42 1.42C16.07 4.74 14.12 4 12 4c-1.83 0-3.53.55-4.95 1.48l1.46 1.46C9.53 6.35 10.73 6 12 6c3.87 0 7 3.13 7 7 0 1.27-.35 2.47-.94 3.49l1.45 1.45C20.45 16.53 21 14.83 21 13c0-2.12-.74-4.07-1.97-5.61l1.42-1.42-1.41-1.42zM15 1H9v2h6V1zm-4 8.44l2 2V8h-2v1.44zM3.02 4L1.75 5.27 4.5 8.03C3.55 9.45 3 11.16 3 13c0 4.97 4.02 9 9 9 1.84 0 3.55-.55 4.98-1.5l2.5 2.5 1.27-1.27-7.71-7.71L3.02 4zM12 20c-3.87 0-7-3.13-7-7 0-1.28.35-2.48.95-3.52l9.56 9.56c-1.03.61-2.23.96-3.51.96z"/> </SvgIcon> ); ImageTimerOff = pure(ImageTimerOff); ImageTimerOff.displayName = 'ImageTimerOff'; ImageTimerOff.muiName = 'SvgIcon'; export default ImageTimerOff;
app/javascript/mastodon/components/load_pending.js
d6rkaiz/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class LoadPending extends React.PureComponent { static propTypes = { onClick: PropTypes.func, count: PropTypes.number, } render() { const { count } = this.props; return ( <button className='load-more load-gap' onClick={this.props.onClick}> <FormattedMessage id='load_pending' defaultMessage='{count, plural, one {# new item} other {# new items}}' values={{ count }} /> </button> ); } }
docs/src/app/components/pages/components/DatePicker/ExampleInline.js
frnk94/material-ui
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; /** * Inline Date Pickers are displayed below the input, rather than as a modal dialog. */ const DatePickerExampleInline = () => ( <div> <DatePicker hintText="Portrait Inline Dialog" container="inline" /> <DatePicker hintText="Landscape Inline Dialog" container="inline" mode="landscape" /> </div> ); export default DatePickerExampleInline;
src/src/Components/RulesEditor/components/Blocks/TriggerState.js
ioBroker/ioBroker.javascript
import React from 'react'; import {withStyles} from '@material-ui/core/styles'; import GenericBlock from '../GenericBlock'; import Compile from '../../helpers/Compile'; import Button from '@material-ui/core/Button'; import Switch from '@material-ui/core/Switch'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import TextField from '@material-ui/core/TextField'; import DialogTitle from '@material-ui/core/DialogTitle'; import Slide from '@material-ui/core/Slide'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import { MdCancel as IconCancel } from 'react-icons/md'; import { MdCheck as IconCheck } from 'react-icons/md'; import I18n from '@iobroker/adapter-react/i18n'; const styles = theme => ({ valueAck: { color: '#b02323' }, valueNotAck: { color: '#12ac15' }, }); const Transition = React.forwardRef((props, ref) => <Slide direction="up" ref={ref} {...props} />); class TriggerState extends GenericBlock { constructor(props) { super(props, TriggerState.getStaticData()); this.inputRef = React.createRef(); } static compile(config, context) { let func = context.justCheck ? Compile.STANDARD_FUNCTION_STATE : Compile.STANDARD_FUNCTION_STATE_ONCHANGE; func = func.replace('"__%%DEBUG_TRIGGER%%__"', `_sendToFrontEnd(${config._id}, {val: obj.state.val, ack: obj.state.ack, valOld: obj.oldState && obj.oldState.val, ackOld: obj.oldState && obj.oldState.ack})`); return `on({id: "${config.oid || ''}", change: "${config.tagCard === 'on update' ? 'any' : 'ne'}"}, ${func});` } static renderValue(val) { if (val === null) { return 'null'; } else if (val === undefined) { return 'undefined'; } else if (Array.isArray(val)) { return val.join(', '); } else if (typeof val === 'object') { return JSON.stringify(val); } else { return val.toString(); } } renderDebug(debugMessage) { if (debugMessage.data.valOld !== undefined) { return <span>{I18n.t('Triggered')} <span className={debugMessage.data.ackOld ? this.props.classes.valueAck : this.props.classes.valueNotAck}>{TriggerState.renderValue(debugMessage.data.valOld)}</span> → <span className={debugMessage.data.ack ? this.props.classes.valueAck : this.props.classes.valueNotAck}>{TriggerState.renderValue(debugMessage.data.val)}</span></span>; } else { return <span>{I18n.t('Triggered')} <span className={debugMessage.data.ack ? this.props.classes.valueAck : this.props.classes.valueNotAck}>{TriggerState.renderValue(debugMessage.data.val)}</span></span>; } } onWriteValue() { this.setState({openSimulate: false}); let simulateValue = this.state.simulateValue; window.localStorage.setItem(`javascript.app.${this.state.settings.oid}_ack`, this.state.simulateAck); if (this.state.settings.oidType === 'boolean') { simulateValue = simulateValue === true || simulateValue === 'true' || simulateValue === '1'; } else if (this.state.settings.oidType === 'number') { simulateValue = parseFloat(simulateValue) || 0; } window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`, simulateValue); this.props.socket.setState(this.state.settings.oid, simulateValue, !!this.state.simulateAck); } renderWriteState() { return <> <Button disabled={!this.state.settings.oid || !this.state.enableSimulation} variant="contained" color="primary" onClick={() => { this.setState({ openSimulate: true, simulateValue: this.state.settings.oidType === 'boolean' ? window.localStorage.getItem('javascript.app.' + this.state.settings.oid) === 'true' : (window.localStorage.getItem('javascript.app.' + this.state.settings.oid) || ''), simulateAck: window.localStorage.getItem(`javascript.app.${this.state.settings.oid}_ack`) === 'true' }); setTimeout(() => this.inputRef.current?.focus(), 200); }}>{I18n.t('Simulate')}</Button> <Dialog open={!!this.state.openSimulate} TransitionComponent={Transition} keepMounted onClose={() => this.setState({openSimulate: false})} aria-labelledby="simulate-dialog-slide-title" aria-describedby="simulate-dialog-slide-description" > <DialogTitle id="simulate-dialog-slide-title">{I18n.t('Trigger with value')}</DialogTitle> <DialogContent> {this.state.settings.oidType === 'boolean' ? <FormControlLabel control={<Switch inputRef={this.inputRef} onKeyUp={e => e.keyCode === 13 && this.onWriteValue()} value={!!this.state.simulateValue} onChange={e => this.setState({simulateValue: e.target.checked})} />} label={I18n.t('Value')} /> : <TextField inputRef={this.inputRef} label={I18n.t('Value')} fullWidth={true} onKeyUp={e => e.keyCode === 13 && this.onWriteValue()} value={this.state.simulateValue} onChange={e => this.setState({simulateValue: e.target.value})} /> } <br/> <FormControlLabel control={ <Checkbox checked={!!this.state.simulateAck} onChange={e => this.setState({simulateAck: e.target.checked})} color="primary" /> } label={I18n.t('Ack')} /> </DialogContent> <DialogActions> <Button variant="contained" onClick={() => this.onWriteValue()} color="primary"> <IconCheck/>{I18n.t('Write')} </Button> <Button variant="contained" onClick={() => this.setState({openSimulate: false})} > <IconCancel/>{I18n.t('Close')} </Button> </DialogActions> </Dialog> </>; } onTagChange(tagCard) { this.setState({ inputs: [ { nameRender: 'renderObjectID', attr: 'oid', defaultValue: '' }, { nameRender: 'renderWriteState', } ] }, () => { super.onTagChange(); }); } static getStaticData() { return { acceptedBy: 'triggers', name: 'State', id: 'TriggerState', icon: 'FlashOn', tagCardArray: ['on change', 'on update'], title: 'Triggers the rule on update or change of some state' // translate } } getData() { return TriggerState.getStaticData(); } } export default withStyles(styles)(TriggerState);
ajax/libs/analytics.js/1.3.7/analytics.min.js
sullivanmatt/cdnjs
(function(){function require(path,parent,orig){var resolved=require.resolve(path);if(null==resolved){orig=orig||path;parent=parent||"root";var err=new Error('Failed to require "'+orig+'" from "'+parent+'"');err.path=orig;err.parent=parent;err.require=true;throw err}var module=require.modules[resolved];if(!module._resolving&&!module.exports){var mod={};mod.exports={};mod.client=mod.component=true;module._resolving=true;module.call(this,mod.exports,require.relative(resolved),mod);delete module._resolving;module.exports=mod.exports}return module.exports}require.modules={};require.aliases={};require.resolve=function(path){if(path.charAt(0)==="/")path=path.slice(1);var paths=[path,path+".js",path+".json",path+"/index.js",path+"/index.json"];for(var i=0;i<paths.length;i++){var path=paths[i];if(require.modules.hasOwnProperty(path))return path;if(require.aliases.hasOwnProperty(path))return require.aliases[path]}};require.normalize=function(curr,path){var segs=[];if("."!=path.charAt(0))return path;curr=curr.split("/");path=path.split("/");for(var i=0;i<path.length;++i){if(".."==path[i]){curr.pop()}else if("."!=path[i]&&""!=path[i]){segs.push(path[i])}}return curr.concat(segs).join("/")};require.register=function(path,definition){require.modules[path]=definition};require.alias=function(from,to){if(!require.modules.hasOwnProperty(from)){throw new Error('Failed to alias "'+from+'", it does not exist')}require.aliases[to]=from};require.relative=function(parent){var p=require.normalize(parent,"..");function lastIndexOf(arr,obj){var i=arr.length;while(i--){if(arr[i]===obj)return i}return-1}function localRequire(path){var resolved=localRequire.resolve(path);return require(resolved,parent,path)}localRequire.resolve=function(path){var c=path.charAt(0);if("/"==c)return path.slice(1);if("."==c)return require.normalize(p,path);var segs=parent.split("/");var i=lastIndexOf(segs,"deps")+1;if(!i)i=0;path=segs.slice(0,i+1).join("/")+"/deps/"+path;return path};localRequire.exists=function(path){return require.modules.hasOwnProperty(localRequire.resolve(path))};return localRequire};require.register("avetisk-defaults/index.js",function(exports,require,module){"use strict";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});require.register("component-type/index.js",function(exports,require,module){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}});require.register("component-clone/index.js",function(exports,require,module){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}}});require.register("component-cookie/index.js",function(exports,require,module){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}});require.register("component-each/index.js",function(exports,require,module){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)}}});require.register("component-indexof/index.js",function(exports,require,module){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}});require.register("component-emitter/index.js",function(exports,require,module){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}});require.register("component-event/index.js",function(exports,require,module){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}});require.register("component-inherit/index.js",function(exports,require,module){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}});require.register("component-object/index.js",function(exports,require,module){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)}});require.register("component-trim/index.js",function(exports,require,module){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}});require.register("component-querystring/index.js",function(exports,require,module){var trim=require("trim");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");obj[parts[0]]=null==parts[1]?"":decodeURIComponent(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]))}return pairs.join("&")}});require.register("component-url/index.js",function(exports,require,module){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);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}}});require.register("component-bind/index.js",function(exports,require,module){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)))}}});require.register("segmentio-bind-all/index.js",function(exports,require,module){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}});require.register("ianstormtaylor-bind/index.js",function(exports,require,module){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");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}});require.register("timoxley-next-tick/index.js",function(exports,require,module){"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)}}});require.register("ianstormtaylor-callback/index.js",function(exports,require,module){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});require.register("ianstormtaylor-is-empty/index.js",function(exports,require,module){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}});require.register("ianstormtaylor-is/index.js",function(exports,require,module){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}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)}}});require.register("segmentio-after/index.js",function(exports,require,module){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}});require.register("yields-slug/index.js",function(exports,require,module){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}});require.register("segmentio-analytics.js-integration/lib/index.js",function(exports,require,module){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this._wrapInitialize();this._wrapLoad();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}});require.register("segmentio-analytics.js-integration/lib/protos.js",function(exports,require,module){var after=require("after");var callback=require("callback");var Emitter=require("emitter");var tick=require("next-tick");var events=require("./events");Emitter(exports);exports.initialize=function(){this.load()};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);try{this.debug("%s with %o",method,args);this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}};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};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;initialize.apply(this,arguments);this.emit("initialize");var self=this;if(this._readyOnInitialize){tick(function(){self.emit("ready")})}};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapLoad=function(){var load=this.load;this.load=function(callback){var self=this;this.debug("loading");if(this.loaded()){this.debug("already loaded");tick(function(){if(self._readyOnLoad)self.emit("ready");callback&&callback()});return}load.call(this,function(err,e){self.debug("loaded");self.emit("load");if(self._readyOnLoad)self.emit("ready");callback&&callback(err,e)})}};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize({category:arguments[0],name:arguments[1],properties:arguments[2],options:arguments[3]})}page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;this[method].apply(this,arguments);called=true;break}if(!called)t.apply(this,arguments)}}});require.register("segmentio-analytics.js-integration/lib/events.js",function(exports,require,module){module.exports={removedProduct:/removed product/i,viewedProduct:/viewed product/i,addedProduct:/added product/i,completedOrder:/completed order/i}});require.register("segmentio-analytics.js-integration/lib/statics.js",function(exports,require,module){var after=require("after");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;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}});require.register("component-domify/index.js",function(exports,require,module){module.exports=parse;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.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=document.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}});require.register("component-once/index.js",function(exports,require,module){var n=0;var global=function(){return this}();module.exports=function(fn){var id=n++;function once(){if(this==global){if(once.called)return;once.called=true;return fn.apply(this,arguments)}var key="__called_"+id+"__";if(this[key])return;this[key]=true;return fn.apply(this,arguments)}return once}});require.register("segmentio-alias/index.js",function(exports,require,module){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}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}});require.register("segmentio-convert-dates/index.js",function(exports,require,module){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}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}});require.register("segmentio-global-queue/index.js",function(exports,require,module){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)}}});require.register("segmentio-load-date/index.js",function(exports,require,module){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time});require.register("segmentio-load-script/index.js",function(exports,require,module){var type=require("type");module.exports=function loadScript(options,callback){if(!options)throw new Error("Cant load nothing...");if(type(options)==="string")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;var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript);if(callback&&type(callback)==="function"){if(script.addEventListener){script.addEventListener("load",function(event){callback(null,event)},false);script.addEventListener("error",function(event){callback(new Error("Failed to load the script."),event)},false)}else if(script.attachEvent){script.attachEvent("onreadystatechange",function(event){if(/complete|loaded/.test(script.readyState)){callback(null,event)}})}}return script}});require.register("segmentio-on-body/index.js",function(exports,require,module){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)}});require.register("segmentio-on-error/index.js",function(exports,require,module){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}}});require.register("segmentio-to-iso-string/index.js",function(exports,require,module){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}});require.register("segmentio-to-unix-timestamp/index.js",function(exports,require,module){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}});require.register("segmentio-use-https/index.js",function(exports,require,module){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:"}});require.register("visionmedia-batch/index.js",function(exports,require,module){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}});require.register("segmentio-substitute/index.js",function(exports,require,module){module.exports=substitute;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){return null!=obj[prop]?obj[prop]:_})}});require.register("segmentio-load-pixel/index.js",function(exports,require,module){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)}}});require.register("segmentio-analytics.js-integrations/index.js",function(exports,require,module){var integrations=require("./lib/slugs");var each=require("each");each(integrations,function(slug){var plugin=require("./lib/"+slug);var name=plugin.Integration.prototype.name;exports[name]=plugin})});require.register("segmentio-analytics.js-integrations/lib/adroll.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(AdRoll);user=analytics.user()};var AdRoll=exports.Integration=integration("AdRoll").assumesPageview().readyOnLoad().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;if(user.id())window.adroll_custom_data={USER_ID:user.id()};window.__adroll_loaded=true;this.load()};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.load=function(callback){load({http:"http://a.adroll.com/j/roundtrip.js",https:"https://s.adroll.com/j/roundtrip.js"},callback)}});require.register("segmentio-analytics.js-integrations/lib/adwords.js",function(exports,require,module){var load=require("load-pixel")("//www.googleadservices.com/pagead/conversion/:id");var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(AdWords)};exports.load=load;var has=Object.prototype.hasOwnProperty;var AdWords=exports.Integration=integration("AdWords").readyOnInitialize().option("conversionId","").option("events",{});AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.options.events;var event=track.event();if(!has.call(events,event))return;return exports.load({value:track.revenue()||0,label:events[event],script:0},{id:id})}});require.register("segmentio-analytics.js-integrations/lib/amplitude.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Amplitude)};var Amplitude=exports.Integration=integration("Amplitude").assumesPageview().readyOnInitialize().global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true);Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load()};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.load=function(callback){load("https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.0-min.js",callback)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)}});require.register("segmentio-analytics.js-integrations/lib/awesm.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Awesm);user=analytics.user()};var Awesm=exports.Integration=integration("awe.sm").assumesPageview().readyOnLoad().global("AWESM").option("apiKey","").option("events",{});Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load()};Awesm.prototype.loaded=function(){return!!window.AWESM._exists};Awesm.prototype.load=function(callback){var key=this.options.apiKey;load("//widgets.awe.sm/v3/widgets.js?key="+key+"&async=true",callback)};Awesm.prototype.track=function(track){var event=track.event();var goal=this.options.events[event];if(!goal)return;window.AWESM.convert(goal,track.cents(),null,user.id())}});require.register("segmentio-analytics.js-integrations/lib/awesomatic.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");var noop=function(){};var onBody=require("on-body");var user;module.exports=exports=function(analytics){analytics.addIntegration(Awesomatic);user=analytics.user()};var Awesomatic=exports.Integration=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","");Awesomatic.prototype.initialize=function(page){var self=this;var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.emit("ready") })})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)};Awesomatic.prototype.load=function(callback){var url="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js";load(url,callback)}});require.register("segmentio-analytics.js-integrations/lib/bing-ads.js",function(exports,require,module){var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(Bing)};var has=Object.prototype.hasOwnProperty;var Bing=exports.Integration=integration("Bing Ads").readyOnInitialize().option("siteId","").option("domainId","").option("goals",{});Bing.prototype.track=function(track){var goals=this.options.goals;var traits=track.traits();var event=track.event();if(!has.call(goals,event))return;var goal=goals[event];return exports.load(goal,track.revenue(),this.options)};exports.load=function(goal,revenue,options){var iframe=document.createElement("iframe");iframe.src="//flex.msn.com/mstag/tag/"+options.siteId+"/analytics.html"+"?domainId="+options.domainId+"&revenue="+revenue||0+"&actionid="+goal;+"&dedup=1"+"&type=1";iframe.width=1;iframe.height=1;return iframe}});require.register("segmentio-analytics.js-integrations/lib/bronto.js",function(exports,require,module){var integration=require("integration");var Track=require("facade").Track;var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(Bronto)};var Bronto=exports.Integration=integration("Bronto").readyOnLoad().global("__bta").option("siteId","").option("host","");Bronto.prototype.initialize=function(page){this.load()};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.load=function(fn){var self=this;load("//p.bm23.com/bta.js",function(err){if(err)return fn(err);var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);fn()})};Bronto.prototype.track=function(track){var revenue=track.revenue();var event=track.event();var type="number"==typeof revenue?"$":"t";this.bta.addConversionLegacy(type,event,revenue)};Bronto.prototype.completedOrder=function(track){var products=track.products();var props=track.properties();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addConversion({order_id:track.orderId(),date:props.date||new Date,items:items})}});require.register("segmentio-analytics.js-integrations/lib/bugherd.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(BugHerd)};var BugHerd=exports.Integration=integration("BugHerd").assumesPageview().readyOnLoad().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true);BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};this.load()};BugHerd.prototype.loaded=function(){return!!window._bugHerd};BugHerd.prototype.load=function(callback){load("//www.bugherd.com/sidebarv2.js?apikey="+this.options.apiKey,callback)}});require.register("segmentio-analytics.js-integrations/lib/bugsnag.js",function(exports,require,module){var integration=require("integration");var is=require("is");var extend=require("extend");var load=require("load-script");var onError=require("on-error");module.exports=exports=function(analytics){analytics.addIntegration(Bugsnag)};var Bugsnag=exports.Integration=integration("Bugsnag").readyOnLoad().global("Bugsnag").option("apiKey","");Bugsnag.prototype.initialize=function(page){this.load()};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.load=function(callback){var apiKey=this.options.apiKey;load("//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js",function(err){if(err)return callback(err);window.Bugsnag.apiKey=apiKey;callback()})};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}});require.register("segmentio-analytics.js-integrations/lib/chartbeat.js",function(exports,require,module){var integration=require("integration");var onBody=require("on-body");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Chartbeat)};var Chartbeat=exports.Integration=integration("Chartbeat").assumesPageview().readyOnLoad().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null);Chartbeat.prototype.initialize=function(page){window._sf_async_config=this.options;onBody(function(){window._sf_endpt=(new Date).getTime()});this.load()};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.load=function(callback){load({https:"https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js",http:"http://static.chartbeat.com/js/chartbeat.js"},callback)};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}});require.register("segmentio-analytics.js-integrations/lib/churnbee.js",function(exports,require,module){var push=require("global-queue")("_cbq");var integration=require("integration");var load=require("load-script");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};module.exports=exports=function(analytics){analytics.addIntegration(ChurnBee)};var ChurnBee=exports.Integration=integration("ChurnBee").readyOnInitialize().global("_cbq").global("ChurnBee").option("events",{}).option("apiKey","");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load()};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.load=function(fn){load("//api.churnbee.com/cb.js",fn)};ChurnBee.prototype.track=function(track){var events=this.options.events;var event=track.event();if(has.call(events,event))event=events[event];if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))}});require.register("segmentio-analytics.js-integrations/lib/clicktale.js",function(exports,require,module){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("integration");var is=require("is");var useHttps=require("use-https");var load=require("load-script");var onBody=require("on-body");module.exports=exports=function(analytics){analytics.addIntegration(ClickTale)};var ClickTale=exports.Integration=integration("ClickTale").assumesPageview().readyOnLoad().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","");ClickTale.prototype.initialize=function(page){var options=this.options;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});this.load(function(){window.ClickTale(options.projectId,options.recordingRatio,options.partitionId)})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.load=function(callback){var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");load({http:http,https:https},callback)};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())}});require.register("segmentio-analytics.js-integrations/lib/clicky.js",function(exports,require,module){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("integration");var is=require("is");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Clicky);user=analytics.user()};var Clicky=exports.Integration=integration("Clicky").assumesPageview().readyOnLoad().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null);Clicky.prototype.initialize=function(page){window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load()};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.load=function(callback){load("//static.getclicky.com/js",callback)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}});require.register("segmentio-analytics.js-integrations/lib/comscore.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Comscore)};var Comscore=exports.Integration=integration("comScore").assumesPageview().readyOnLoad().global("_comscore").global("COMSCORE").option("c1","2").option("c2","");Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];this.load()};Comscore.prototype.loaded=function(){return!!window.COMSCORE};Comscore.prototype.load=function(callback){load({http:"http://b.scorecardresearch.com/beacon.js",https:"https://sb.scorecardresearch.com/beacon.js"},callback)}});require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(CrazyEgg)};var CrazyEgg=exports.Integration=integration("Crazy Egg").assumesPageview().readyOnLoad().global("CE2").option("accountNumber","");CrazyEgg.prototype.initialize=function(page){this.load()};CrazyEgg.prototype.loaded=function(){return!!window.CE2};CrazyEgg.prototype.load=function(callback){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);var url="//dnn506yrbagrg.cloudfront.net/pages/scripts/"+path+".js?"+cache;load(url,callback)}});require.register("segmentio-analytics.js-integrations/lib/curebit.js",function(exports,require,module){var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var integration=require("integration");var Track=require("facade").Track;var iso=require("to-iso-string");var load=require("load-script");var extend=require("extend");var clone=require("clone");var each=require("each");var user;module.exports=exports=function(analytics){analytics.addIntegration(Curebit);user=analytics.user()};var Curebit=exports.Integration=integration("Curebit").readyOnInitialize().global("_curebitq").global("curebit").option("siteId","").option("iframeWidth",0).option("iframeHeight",0).option("iframeBorder",0).option("iframeId","").option("responsive",true).option("device","").option("server","https://www.curebit.com");Curebit.prototype.initialize=function(){push("init",{site_id:this.options.siteId,server:this.options.server});this.load()};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.load=function(fn){load("//d2jjzw81hqbuqv.cloudfront.net/assets/api/all-0.6.js",fn)};Curebit.prototype.identify=function(identify){push("register_affiliate",{responsive:this.options.responsive,device:this.options.device,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder},affiliate_member:{email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}})};Curebit.prototype.completedOrder=function(track){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})}});require.register("segmentio-analytics.js-integrations/lib/customerio.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Customerio);user=analytics.user()};var Customerio=exports.Integration=integration("Customer.io").assumesPageview().readyOnInitialize().global("_cio").option("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()};Customerio.prototype.loaded=function(){return!!(window._cio&&window._cio.pageHasLoaded)};Customerio.prototype.load=function(callback){var script=load("https://assets.customer.io/assets/track.js",callback);script.id="cio-tracker";script.setAttribute("data-site-id",this.options.siteId)};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();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)}});require.register("segmentio-analytics.js-integrations/lib/drip.js",function(exports,require,module){var alias=require("alias");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");module.exports=exports=function(analytics){analytics.addIntegration(Drip)};var Drip=exports.Integration=integration("Drip").assumesPageview().readyOnLoad().global("dc").global("_dcq").global("_dcs").option("account","");Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load()};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.load=function(callback){load("//tag.getdrip.com/"+this.options.account+".js",callback)};Drip.prototype.track=function(track){var props=track.properties();var cents=Math.round(track.cents());props.action=track.event();if(cents)props.value=cents;delete props.revenue;push("track",props)}});require.register("segmentio-analytics.js-integrations/lib/errorception.js",function(exports,require,module){var callback=require("callback");var extend=require("extend");var integration=require("integration");var load=require("load-script");var onError=require("on-error");var push=require("global-queue")("_errs");module.exports=exports=function(analytics){analytics.addIntegration(Errorception)};var Errorception=exports.Integration=integration("Errorception").assumesPageview().readyOnInitialize().global("_errs").option("projectId","").option("meta",true);Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load()};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.load=function(callback){load("//beacon.errorception.com/"+this.options.projectId+".js",callback)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}});require.register("segmentio-analytics.js-integrations/lib/evergage.js",function(exports,require,module){var each=require("each");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_aaq");module.exports=exports=function(analytics){analytics.addIntegration(Evergage)};var Evergage=exports.Integration=integration("Evergage").assumesPageview().readyOnInitialize().global("_aaq").option("account","").option("dataset","");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()};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.load=function(callback){var account=this.options.account;var dataset=this.options.dataset;var url="//cdn.evergage.com/beacon/"+account+"/"+dataset+"/scripts/evergage.min.js";load(url,callback)};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())}});require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js",function(exports,require,module){var load=require("load-pixel")("//www.facebook.com/offsite_event.php");var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(Facebook)};exports.load=load;var has=Object.prototype.hasOwnProperty;var Facebook=exports.Integration=integration("Facebook Ads").readyOnInitialize().option("currency","USD").option("events",{});Facebook.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();if(!has.call(events,event))return;return exports.load({currency:this.options.currency,value:track.revenue()||0,id:events[event]})}});require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js",function(exports,require,module){var push=require("global-queue")("_fxm");var integration=require("integration");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(FoxMetrics)};var FoxMetrics=exports.Integration=integration("FoxMetrics").assumesPageview().readyOnInitialize().global("_fxm").option("appId","");FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load()};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.load=function(callback){var id=this.options.appId;load("//d35tca7vmefkrc.cloudfront.net/scripts/"+id+".js",callback)};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||[]))}});require.register("segmentio-analytics.js-integrations/lib/gauges.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_gauges");module.exports=exports=function(analytics){analytics.addIntegration(Gauges)};var Gauges=exports.Integration=integration("Gauges").assumesPageview().readyOnInitialize().global("_gauges").option("siteId","");Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load()};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.load=function(callback){var id=this.options.siteId;var script=load("//secure.gaug.es/track.js",callback);script.id="gauges-tracker";script.setAttribute("data-site-id",id)};Gauges.prototype.page=function(page){push("track")}});require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var onBody=require("on-body");module.exports=exports=function(analytics){analytics.addIntegration(GetSatisfaction)};var GetSatisfaction=exports.Integration=integration("Get Satisfaction").assumesPageview().readyOnLoad().global("GSFN").option("widgetId","");GetSatisfaction.prototype.initialize=function(page){var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id})})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN};GetSatisfaction.prototype.load=function(callback){load("https://loader.engage.gsfn.us/loader.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/google-analytics.js",function(exports,require,module){var callback=require("callback");var canonical=require("canonical");var each=require("each");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_gaq");var Track=require("facade").Track;var type=require("type");var url=require("url");var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoreReferrer",null).option("includeSearch",false).option("siteSpeedSampleRate",null).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false);GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.load=integration.loadClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(this.options.sendUserId&&user.id()){window.ga("set","&uid",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);this.load()};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.load=function(callback){load("//www.google-analytics.com/analytics.js",callback)};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();window.ga("send","event",{eventAction:event,eventCategory:this._category||props.category||"All",eventLabel:props.label,eventValue:formatValue(props.value||revenue),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce","ecommerce.js");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:track.total(),tax:track.tax(),id:orderId});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})});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.ignoreReferrer;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}this.load()};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.loadClassic=function(callback){if(this.options.doubleClick){load("//stats.g.doubleclick.net/dc.js",callback)}else{load({http:"http://www.google-analytics.com/ga.js",https:"https://ssl.google-analytics.com/ga.js"},callback)}};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var orderId=track.orderId();var products=track.products()||[];var props=track.properties();if(!orderId)return;push("_addTrans",orderId,props.affiliation,track.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("_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)}});require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js",function(exports,require,module){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(GTM)};var GTM=exports.Integration=integration("Google Tag Manager").assumesPageview().readyOnLoad().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true);GTM.prototype.initialize=function(){this.load()};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.load=function(fn){var id=this.options.containerId;push({"gtm.start":+new Date,event:"gtm.js"});load("//www.googletagmanager.com/gtm.js?id="+id+"&l=dataLayer",fn)};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)}});require.register("segmentio-analytics.js-integrations/lib/gosquared.js",function(exports,require,module){var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var integration=require("integration");var load=require("load-script");var onBody=require("on-body");var each=require("each");var user;module.exports=exports=function(analytics){analytics.addIntegration(GoSquared);user=analytics.user()};var GoSquared=exports.Integration=integration("GoSquared").assumesPageview().readyOnLoad().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true);GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;push(options.siteToken); each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load()};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.load=function(callback){load("//d1l6p2sc9645hc.cloudfront.net/tracker.js",callback)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}});require.register("segmentio-analytics.js-integrations/lib/heap.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Heap)};var Heap=exports.Integration=integration("Heap").assumesPageview().readyOnInitialize().global("heap").global("_heapid").option("apiKey","");Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load()};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.load=function(callback){load("//d36lvucg9kzous.cloudfront.net",callback)};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/hittail.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(HitTail)};var HitTail=exports.Integration=integration("HitTail").assumesPageview().readyOnLoad().global("htk").option("siteId","");HitTail.prototype.initialize=function(page){this.load()};HitTail.prototype.loaded=function(){return is.fn(window.htk)};HitTail.prototype.load=function(callback){var id=this.options.siteId;load("//"+id+".hittail.com/mlt.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/hubspot.js",function(exports,require,module){var callback=require("callback");var convert=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_hsq");module.exports=exports=function(analytics){analytics.addIntegration(HubSpot)};var HubSpot=exports.Integration=integration("HubSpot").assumesPageview().readyOnInitialize().global("_hsq").option("portalId",null);HubSpot.prototype.initialize=function(page){window._hsq=[];this.load()};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.load=function(fn){if(document.getElementById("hs-analytics"))return callback.async(fn);var id=this.options.portalId;var cache=Math.ceil(new Date/3e5)*3e5;var url="https://js.hs-analytics.net/analytics/"+cache+"/"+id+".js";var script=load(url,fn);script.id="hs-analytics"};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()})}});require.register("segmentio-analytics.js-integrations/lib/improvely.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Improvely)};var Improvely=exports.Integration=integration("Improvely").assumesPageview().readyOnInitialize().global("_improvely").global("improvely").option("domain","").option("projectId",null);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()};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.load=function(callback){var domain=this.options.domain;load("//"+domain+".iljmp.com/improvely.js",callback)};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)}});require.register("segmentio-analytics.js-integrations/lib/inspectlet.js",function(exports,require,module){var integration=require("integration");var alias=require("alias");var clone=require("clone");var load=require("load-script");var push=require("global-queue")("__insp");module.exports=exports=function(analytics){analytics.addIntegration(Inspectlet)};var Inspectlet=exports.Integration=integration("Inspectlet").assumesPageview().readyOnLoad().global("__insp").global("__insp_").option("wid","");Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load()};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.load=function(callback){load("//www.inspectlet.com/inspectlet.js",callback)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}});require.register("segmentio-analytics.js-integrations/lib/intercom.js",function(exports,require,module){var alias=require("alias");var convertDates=require("convert-dates");var integration=require("integration");var each=require("each");var is=require("is");var isEmail=require("is-email");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Intercom)};var Intercom=exports.Integration=integration("Intercom").assumesPageview().readyOnLoad().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false);Intercom.prototype.initialize=function(page){this.load()};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.load=function(callback){load("https://static.intercomcdn.com/intercom.v1.js",callback)};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(name)traits.name=name;if(companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company){traits.company=alias(traits.company,{created:"created_at"})}if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if(this.options.inbox){traits.widget={activator:this.options.activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackUserEvent",track.event(),track.traits())};function formatDate(date){return Math.floor(date/1e3)}});require.register("segmentio-analytics.js-integrations/lib/keen-io.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Keen)};var Keen=exports.Integration=integration("Keen IO").readyOnInitialize().global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true);Keen.prototype.initialize=function(){var options=this.options;window.Keen=window.Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};window.Keen.configure({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});this.load()};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.Base64)};Keen.prototype.load=function(callback){load("//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js",callback)};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;window.Keen.setGlobalProperties(function(){return{user:user}})};Keen.prototype.track=function(track){window.Keen.addEvent(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js",function(exports,require,module){var alias=require("alias");var Batch=require("batch");var callback=require("callback");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(KISSmetrics)};var KISSmetrics=exports.Integration=integration("KISSmetrics").assumesPageview().readyOnInitialize().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true);KISSmetrics.prototype.initialize=function(page){window._kmq=[];this.load()};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.load=function(callback){var key=this.options.apiKey;var useless="//i.kissmetrics.com/i.js";var library="//doug1izaerwt3.cloudfront.net/"+key+".1.js";(new Batch).push(function(done){load(useless,done)}).push(function(done){load(library,done)}).end(callback)};KISSmetrics.prototype.page=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 props=track.properties({revenue:"Billing Amount"});push("record",track.event(),props)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.viewedProduct=function(track){push("record","Product Viewed",toProduct(track))};KISSmetrics.prototype.addedProduct=function(track){push("record","Product Added",toProduct(track))};KISSmetrics.prototype.completedOrder=function(track){var orderId=track.orderId();var products=track.products();push("record","Purchased",{"Order ID":track.orderId(),"Order Total":track.total()});window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var track=new Track({properties:product});var item=toProduct(track);item["Order ID"]=orderId;item._t=km.ts()+i;item._d=1;km.set(item)})})};function toProduct(track){return{Quantity:track.quantity(),Price:track.price(),Name:track.name(),SKU:track.sku()}}});require.register("segmentio-analytics.js-integrations/lib/klaviyo.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_learnq");module.exports=exports=function(analytics){analytics.addIntegration(Klaviyo)};var Klaviyo=exports.Integration=integration("Klaviyo").assumesPageview().readyOnInitialize().global("_learnq").option("apiKey","");Klaviyo.prototype.initialize=function(page){push("account",this.options.apiKey);this.load()};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.load=function(callback){load("//a.klaviyo.com/media/js/learnmarklet.js",callback)};var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};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())}});require.register("segmentio-analytics.js-integrations/lib/leadlander.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(LeadLander)};var LeadLander=exports.Integration=integration("LeadLander").assumesPageview().readyOnLoad().global("llactid").global("trackalyzer").option("accountId",null);LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load()};LeadLander.prototype.loaded=function(){return!!window.trackalyzer};LeadLander.prototype.load=function(callback){load("http://t6.trackalyzer.com/trackalyze-nodoc.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/livechat.js",function(exports,require,module){var each=require("each");var integration=require("integration");var load=require("load-script");var clone=require("clone");module.exports=exports=function(analytics){analytics.addIntegration(LiveChat)};var LiveChat=exports.Integration=integration("LiveChat").assumesPageview().readyOnLoad().global("__lc").option("group",0).option("license","");LiveChat.prototype.initialize=function(page){window.__lc=clone(this.options);this.isLoaded=false;this.load()};LiveChat.prototype.loaded=function(){return this.isLoaded};LiveChat.prototype.load=function(callback){var self=this;load("//cdn.livechatinc.com/tracking.js",function(err){if(err)return callback(err);self.isLoaded=true;callback()})};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}});require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js",function(exports,require,module){var Identify=require("facade").Identify;var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(LuckyOrange);user=analytics.user()};var LuckyOrange=exports.Integration=integration("Lucky Orange").assumesPageview().readyOnLoad().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null);LuckyOrange.prototype.initialize=function(page){window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));this.load()};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.load=function(callback){var cache=Math.floor((new Date).getTime()/6e4);load({http:"http://www.luckyorange.com/w.js?"+cache,https:"https://ssl.luckyorange.com/w.js?"+cache},callback)};LuckyOrange.prototype.identify=function(identify){var traits=window.__wtw_custom_user_data=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email}});require.register("segmentio-analytics.js-integrations/lib/lytics.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Lytics)};var Lytics=exports.Integration=integration("Lytics").readyOnInitialize().global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io");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()};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.load=function(callback){load("//c.lytics.io/static/io.min.js",callback)};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)}});require.register("segmentio-analytics.js-integrations/lib/mixpanel.js",function(exports,require,module){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("integration");var iso=require("to-iso-string");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Mixpanel)};var Mixpanel=exports.Integration=integration("Mixpanel").readyOnLoad().global("mixpanel").option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true);var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load()};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.load=function(callback){load("//cdn.mxpnl.com/libs/mixpanel-2.2.min.js",callback)};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);traits=identify.traits(traitAliases);window.mixpanel.register(traits);if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&this.options.people){window.mixpanel.people.track_charge(revenue)}};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())}});require.register("segmentio-analytics.js-integrations/lib/mojn.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Mojn)};var Mojn=exports.Integration=integration("Mojn").option("customerCode","").global("_agTrack").readyOnInitialize();Mojn.prototype.initialize=function(){window._agTrack=window._agTrack||[];window._agTrack.push({cid:this.options.customerCode});this.load()};Mojn.prototype.load=function(fn){load("https://track.idtargeting.com/"+this.options.customerCode+"/track.js",fn)};Mojn.prototype.loaded=function(){return is.object(window._agTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._agTrack.push({conv:conv});return conv}});require.register("segmentio-analytics.js-integrations/lib/mouseflow.js",function(exports,require,module){var push=require("global-queue")("_mfq");var integration=require("integration");var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(Mouseflow)};var Mouseflow=exports.Integration=integration("Mouseflow").assumesPageview().readyOnLoad().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0);Mouseflow.prototype.initialize=function(page){this.load()};Mouseflow.prototype.loaded=function(){return!!(window._mfq&&[].push!=window._mfq.push)};Mouseflow.prototype.load=function(fn){var apiKey=this.options.apiKey;window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;load("//cdn.mouseflow.com/projects/"+apiKey+".js",fn)};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(hash){each(hash,function(k,v){push("setVariable",k,v)})}});require.register("segmentio-analytics.js-integrations/lib/mousestats.js",function(exports,require,module){var each=require("each");var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(MouseStats)};var MouseStats=exports.Integration=integration("MouseStats").assumesPageview().readyOnLoad().global("msaa").option("accountNumber","");MouseStats.prototype.initialize=function(page){this.load()};MouseStats.prototype.loaded=function(){return is.fn(window.msaa)};MouseStats.prototype.load=function(callback){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var partial=".mousestats.com/js/"+path+".js?"+cache;var http="http://www2"+partial;var https="https://ssl"+partial;load({http:http,https:https},callback)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}});require.register("segmentio-analytics.js-integrations/lib/olark.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var https=require("use-https");module.exports=exports=function(analytics){analytics.addIntegration(Olark)};var Olark=exports.Integration=integration("Olark").assumesPageview().readyOnInitialize().global("olark").option("identify",true).option("page",true).option("siteId","").option("track",false);Olark.prototype.initialize=function(page){window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);var self=this;box("onExpand",function(){self._open=true});box("onShrink",function(){self._open=false})};Olark.prototype.page=function(page){if(!this.options.page||!this._open)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;var msg=name?name.toLowerCase()+" page":props.url;chat("sendNotificationToOperator",{body:"looking at "+msg})};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();visitor("updateCustomFields",traits);if(email)visitor("updateEmailAddress",{emailAddress:email});if(phone)visitor("updatePhoneNumber",{phoneNumber:phone});if(name)visitor("updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)chat("updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track||!this._open)return;chat("sendNotificationToOperator",{body:'visitor triggered "'+track.event()+'"'})};function box(action,value){window.olark("api.box."+action,value)}function visitor(action,value){window.olark("api.visitor."+action,value)}function chat(action,value){window.olark("api.chat."+action,value)}});require.register("segmentio-analytics.js-integrations/lib/optimizely.js",function(exports,require,module){var bind=require("bind");var callback=require("callback");var each=require("each");var integration=require("integration");var push=require("global-queue")("optimizely");var tick=require("next-tick");var analytics;module.exports=exports=function(ajs){ajs.addIntegration(Optimizely);analytics=ajs};var Optimizely=exports.Integration=integration("Optimizely").readyOnInitialize().option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations)tick(this.replay)};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});analytics.identify(traits)}});require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(PerfectAudience)};var PerfectAudience=exports.Integration=integration("Perfect Audience").assumesPageview().readyOnLoad().global("_pa").option("siteId","");PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load()};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.load=function(callback){var id=this.options.siteId;load("//tag.perfectaudience.com/serve/"+id+".js",callback)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/pingdom.js",function(exports,require,module){var date=require("load-date");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_prum");module.exports=exports=function(analytics){analytics.addIntegration(Pingdom)};var Pingdom=exports.Integration=integration("Pingdom").assumesPageview().readyOnLoad().global("_prum").option("id","");Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());this.load()};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)};Pingdom.prototype.load=function(callback){load("//rum-static.pingdom.net/prum.min.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/preact.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script"); var push=require("global-queue")("_lnq");module.exports=exports=function(analytics){analytics.addIntegration(Preact)};var Preact=exports.Integration=integration("Preact").assumesPageview().readyOnInitialize().global("_lnq").option("projectCode","");Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load()};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.load=function(callback){load("//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js",callback)};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)}});require.register("segmentio-analytics.js-integrations/lib/qualaroo.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;module.exports=exports=function(analytics){analytics.addIntegration(Qualaroo)};var Qualaroo=exports.Integration=integration("Qualaroo").assumesPageview().readyOnInitialize().global("_kiq").option("customerId","").option("siteToken","").option("track",false);Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];this.load()};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.load=function(callback){var token=this.options.siteToken;var id=this.options.customerId;load("//s3.amazonaws.com/ki.js/"+id+"/"+token+".js",callback)};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}))}});require.register("segmentio-analytics.js-integrations/lib/quantcast.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_qevents",{wrap:false});var user;module.exports=exports=function(analytics){analytics.addIntegration(Quantcast);user=analytics.user()};var Quantcast=exports.Integration=integration("Quantcast").assumesPageview().readyOnInitialize().global("_qevents").global("__qc").option("pCode",null).option("labelPages",false);Quantcast.prototype.initialize=function(page){page=page||{};window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};if(user.id())settings.uid=user.id();push(settings);this.load()};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.load=function(callback){load({http:"http://edge.quantserve.com/quant.js",https:"https://secure.quantserve.com/quant.js"},callback)};Quantcast.prototype.page=function(page){var settings={event:"refresh",qacct:this.options.pCode};if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id)window._qevents[0].uid=id};Quantcast.prototype.track=function(track){var settings={event:"click",qacct:this.options.pCode};if(user.id())settings.uid=user.id();push(settings)}});require.register("segmentio-analytics.js-integrations/lib/rollbar.js",function(exports,require,module){var callback=require("callback");var clone=require("clone");var extend=require("extend");var integration=require("integration");var load=require("load-script");var onError=require("on-error");module.exports=exports=function(analytics){analytics.addIntegration(Rollbar)};var Rollbar=exports.Integration=integration("Rollbar").readyOnInitialize().assumesPageview().global("_rollbar").option("accessToken","").option("identify",true);Rollbar.prototype.initialize=function(page){var options=this.options;window._rollbar=window._rollbar||window._ratchet||[options.accessToken,options];onError(function(){window._rollbar.push.apply(window._rollbar,arguments)});this.load()};Rollbar.prototype.loaded=function(){return!!(window._rollbar&&window._rollbar.push!==Array.prototype.push)};Rollbar.prototype.load=function(callback){load("//d37gvrvc0wt4s1.cloudfront.net/js/1/rollbar.min.js",callback)};Rollbar.prototype.identify=function(identify){if(!this.options.identify)return;var traits=identify.traits();var rollbar=window._rollbar;var params=rollbar.shift?rollbar[1]=rollbar[1]||{}:rollbar.extraParams=rollbar.extraParams||{};params.person=params.person||{};extend(params.person,traits)}});require.register("segmentio-analytics.js-integrations/lib/saasquatch.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(SaaSquatch)};var SaaSquatch=exports.Integration=integration("SaaSquatch").readyOnInitialize().option("tenantAlias","").global("_sqh");SaaSquatch.prototype.initialize=function(page){};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.load=function(fn){load("//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js",fn)};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh=window._sqh||[];var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}});require.register("segmentio-analytics.js-integrations/lib/sentry.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Sentry)};var Sentry=exports.Integration=integration("Sentry").readyOnLoad().global("Raven").option("config","");Sentry.prototype.initialize=function(){var config=this.options.config;this.load(function(){window.Raven.config(config).install()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.load=function(callback){load("//cdn.ravenjs.com/1.1.10/native/raven.min.js",callback)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}});require.register("segmentio-analytics.js-integrations/lib/snapengage.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(SnapEngage)};var SnapEngage=exports.Integration=integration("SnapEngage").assumesPageview().readyOnLoad().global("SnapABug").option("apiKey","");SnapEngage.prototype.initialize=function(page){this.load()};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.load=function(callback){var key=this.options.apiKey;var url="//commondatastorage.googleapis.com/code.snapengage.com/js/"+key+".js";load(url,callback)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}});require.register("segmentio-analytics.js-integrations/lib/spinnakr.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Spinnakr)};var Spinnakr=exports.Integration=integration("Spinnakr").assumesPageview().readyOnLoad().global("_spinnakr_site_id").global("_spinnakr").option("siteId","");Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;this.load()};Spinnakr.prototype.loaded=function(){return!!window._spinnakr};Spinnakr.prototype.load=function(callback){load("//d3ojzyhbolvoi5.cloudfront.net/js/so.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/tapstream.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var slug=require("slug");var push=require("global-queue")("_tsq");module.exports=exports=function(analytics){analytics.addIntegration(Tapstream)};var Tapstream=exports.Integration=integration("Tapstream").assumesPageview().readyOnInitialize().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load()};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.load=function(callback){load("//cdn.tapstream.com/static/js/tapstream.js",callback)};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])}});require.register("segmentio-analytics.js-integrations/lib/trakio.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var clone=require("clone");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Trakio)};var Trakio=exports.Integration=integration("trak.io").assumesPageview().readyOnInitialize().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true);var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var self=this;var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.io.load=function(e){self.load();var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load()};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.load=function(callback){load("//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js",callback)};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)}}});require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js",function(exports,require,module){var pixel=require("load-pixel")("//analytics.twitter.com/i/adsct");var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(TwitterAds)};exports.load=pixel;var has=Object.prototype.hasOwnProperty;var TwitterAds=exports.Integration=integration("Twitter Ads").readyOnInitialize().option("events",{});TwitterAds.prototype.track=function(track){var events=this.options.events;var event=track.event();if(!has.call(events,event))return;return exports.load({txn_id:events[event],p_id:"Twitter"})}});require.register("segmentio-analytics.js-integrations/lib/usercycle.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_uc");module.exports=exports=function(analytics){analytics.addIntegration(Usercycle)};var Usercycle=exports.Integration=integration("USERcycle").assumesPageview().readyOnInitialize().global("_uc").option("key","");Usercycle.prototype.initialize=function(page){push("_key",this.options.key);this.load()};Usercycle.prototype.loaded=function(){return!!(window._uc&&window._uc.push!==Array.prototype.push)};Usercycle.prototype.load=function(callback){load("//api.usercycle.com/javascripts/track.js",callback)};Usercycle.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("uid",id);push("action","came_back",traits)};Usercycle.prototype.track=function(track){push("action",track.event(),track.properties({revenue:"revenue_amount"}))}});require.register("segmentio-analytics.js-integrations/lib/userfox.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_ufq");module.exports=exports=function(analytics){analytics.addIntegration(Userfox)};var Userfox=exports.Integration=integration("userfox").assumesPageview().readyOnInitialize().global("_ufq").option("clientId","");Userfox.prototype.initialize=function(page){window._ufq=[];this.load()};Userfox.prototype.loaded=function(){return!!(window._ufq&&window._ufq.push!==Array.prototype.push)};Userfox.prototype.load=function(callback){load("//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js",callback)};Userfox.prototype.identify=function(identify){var traits=identify.traits({created:"signup_date"});var email=identify.email();if(!email)return;push("init",{clientId:this.options.clientId,email:email});traits=convertDates(traits,formatDate);push("track",traits)};function formatDate(date){return Math.round(date.getTime()/1e3).toString()}});require.register("segmentio-analytics.js-integrations/lib/uservoice.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var clone=require("clone");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("UserVoice");var unix=require("to-unix-timestamp");module.exports=exports=function(analytics){analytics.addIntegration(UserVoice)};var UserVoice=exports.Integration=integration("UserVoice").assumesPageview().readyOnInitialize().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").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);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()};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.load=function(callback){var key=this.options.apiKey;load("//widget.uservoice.com/"+key+".js",callback)};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()};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}});require.register("segmentio-analytics.js-integrations/lib/vero.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_veroq");module.exports=exports=function(analytics){analytics.addIntegration(Vero)};var Vero=exports.Integration=integration("Vero").assumesPageview().readyOnInitialize().global("_veroq").option("apiKey","");Vero.prototype.initialize=function(pgae){push("init",{api_key:this.options.apiKey});this.load()};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.load=function(callback){load("//d3qxef4rp70elm.cloudfront.net/m.js",callback)};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js",function(exports,require,module){var callback=require("callback");var each=require("each");var integration=require("integration");var tick=require("next-tick");var analytics;module.exports=exports=function(ajs){ajs.addIntegration(VWO);analytics=ajs};var VWO=exports.Integration=integration("Visual Website Optimizer").readyOnInitialize().option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay()};VWO.prototype.replay=function(){tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(callback){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return callback();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});callback(null,data)})}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}});require.register("segmentio-analytics.js-integrations/lib/webengage.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(WebEngage)};var WebEngage=exports.Integration=integration("WebEngage").assumesPageview().readyOnLoad().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","");WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;this.load()};WebEngage.prototype.loaded=function(){return!!window.webengage};WebEngage.prototype.load=function(fn){var path="/js/widget/webengage-min-v-4.0.js";load({https:"https://ssl.widgets.webengage.com"+path,http:"http://cdn.widgets.webengage.com"+path},fn)}});require.register("segmentio-analytics.js-integrations/lib/woopra.js",function(exports,require,module){var each=require("each");var extend=require("extend");var integration=require("integration");var isEmail=require("is-email");var load=require("load-script");var type=require("type");module.exports=exports=function(analytics){analytics.addIntegration(Woopra)};var Woopra=exports.Integration=integration("Woopra").readyOnLoad().global("woopra").option("domain","");Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");window.woopra.config({domain:this.options.domain});this.load()};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.load=function(callback){load("//static.woopra.com/js/w.js",callback)};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){window.woopra.identify(identify.traits()).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Yandex)};var Yandex=exports.Integration=integration("Yandex Metrica").assumesPageview().readyOnInitialize().global("yandex_metrika_callbacks").global("Ya").option("counterId",null);Yandex.prototype.initialize=function(page){var id=this.options.counterId;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id})});this.load()};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};Yandex.prototype.load=function(callback){load("//mc.yandex.ru/metrika/watch.js",callback)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}});require.register("segmentio-canonical/index.js",function(exports,require,module){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}});require.register("segmentio-extend/index.js",function(exports,require,module){module.exports=function extend(object){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}});require.register("camshaft-require-component/index.js",function(exports,require,module){module.exports=function(parent){function require(name,fallback){try{return parent(name)}catch(e){try{return parent(fallback||name+"-component")}catch(e2){throw e}}}for(var key in parent){require[key]=parent[key]}return require}});require.register("ianstormtaylor-to-camel-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-capital-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}});require.register("ianstormtaylor-to-constant-case/index.js",function(exports,require,module){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}});require.register("ianstormtaylor-to-dot-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}});require.register("ianstormtaylor-to-no-case/index.js",function(exports,require,module){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(" ")})}});require.register("ianstormtaylor-to-pascal-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-sentence-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-slug-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}});require.register("ianstormtaylor-to-snake-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}});require.register("ianstormtaylor-to-space-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}});require.register("component-escape-regexp/index.js",function(exports,require,module){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}});require.register("ianstormtaylor-map/index.js",function(exports,require,module){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}});require.register("ianstormtaylor-title-case-minors/index.js",function(exports,require,module){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]});require.register("ianstormtaylor-to-title-case/index.js",function(exports,require,module){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-case/lib/index.js",function(exports,require,module){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}});require.register("ianstormtaylor-case/lib/cases.js",function(exports,require,module){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none});require.register("segmentio-obj-case/index.js",function(exports,require,module){var Case=require("case");var cases=[Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}});require.register("segmentio-facade/lib/index.js",function(exports,require,module){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")});require.register("segmentio-facade/lib/alias.js",function(exports,require,module){var Facade=require("./facade");var component=require("require-component")(require);var inherit=component("inherit");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Facade.field("from");Alias.prototype.to=Facade.field("to")});require.register("segmentio-facade/lib/facade.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var isEnabled=component("./is-enabled");var objCase=component("obj-case");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=new Date(obj.timestamp);this.obj=obj}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 clone(obj);obj=objCase(obj,fields.join("."));return clone(obj)};Facade.prototype.field=function(field){return clone(this.obj[field])};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.prototype.json=function(){return clone(this.obj)};Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;options=options[integration]||objCase(options,integration)||{};return typeof options==="boolean"?{}:clone(options)};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.options();if(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.userAgent=function(){};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.userId=Facade.field("userId");Facade.prototype.sessionId=Facade.field("sessionId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.ip=Facade.proxy("options.ip")});require.register("segmentio-facade/lib/group.js",function(exports,require,module){var Facade=require("./facade");var component=require("require-component")(require);var inherit=component("inherit");var newDate=component("new-date");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);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.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.properties=function(){return this.field("traits")||this.field("properties")||{}}});require.register("segmentio-facade/lib/page.js",function(exports,require,module){var component=require("require-component")(require);var Facade=component("./facade");var inherit=component("inherit");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");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),properties:props})}});require.register("segmentio-facade/lib/identify.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var Facade=component("./facade");var inherit=component("inherit");var isEmail=component("is-email");var newDate=component("new-date");var trim=component("trim");module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);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;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.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.proxy("traits.website");Identify.prototype.phone=Facade.proxy("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.avatar=Facade.proxy("traits.avatar")});require.register("segmentio-facade/lib/is-enabled.js",function(exports,require,module){var disabled={Salesforce:true,Marketo:true};module.exports=function(integration){return!disabled[integration]}});require.register("segmentio-facade/lib/track.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var Facade=component("./facade");var Identify=component("./identify");var inherit=component("inherit");var isEmail=component("is-email");var traverse=component("isodate-traverse");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);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.country=Facade.proxy("properties.country");Track.prototype.state=Facade.proxy("properties.state");Track.prototype.city=Facade.proxy("properties.city");Track.prototype.zip=Facade.proxy("properties.zip");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.orderId=Facade.proxy("properties.orderId");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=this.obj.properties.subtotal;var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;return total};Track.prototype.products=function(){var props=this.obj.properties||{};return props.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 clone(traverse(ret))};Track.prototype.traits=function(){return this.proxy("options.traits")||{}};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");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");if(!revenue)return;if(typeof revenue==="number")return revenue;if(typeof revenue!=="string")return;revenue=revenue.replace(/\$/g,"");revenue=parseFloat(revenue);if(!isNaN(revenue))return revenue};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)}});require.register("segmentio-is-email/index.js",function(exports,require,module){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}});require.register("segmentio-is-meta/index.js",function(exports,require,module){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}});require.register("segmentio-isodate/index.js",function(exports,require,module){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,8,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]--;if(arr[8])arr[8]=(arr[8]+"00").substring(0,3);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)}});require.register("segmentio-isodate-traverse/index.js",function(exports,require,module){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input)){return object(input,strict)}else if(is.array(input)){return array(input,strict)}}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}});require.register("component-json-fallback/index.js",function(exports,require,module){if(typeof JSON!=="object"){JSON={}}(function(){"use strict";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")}}})();module.exports=JSON});require.register("segmentio-json/index.js",function(exports,require,module){module.exports="undefined"==typeof JSON?require("json-fallback"):JSON});require.register("segmentio-new-date/lib/index.js",function(exports,require,module){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");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}});require.register("segmentio-new-date/lib/milliseconds.js",function(exports,require,module){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}});require.register("segmentio-new-date/lib/seconds.js",function(exports,require,module){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)}});require.register("segmentio-store.js/store.js",function(exports,require,module){(function(win){var store={},doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return JSON.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return JSON.parse(value)}catch(e){return value||undefined}};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;if(typeof module!="undefined"&&module.exports){module.exports=store}else if(typeof define==="function"&&define.amd){define(store)}else{win.store=store}})(this.window||global)});require.register("segmentio-top-domain/index.js",function(exports,require,module){var url=require("url");module.exports=function(urlStr){var host=url.parse(urlStr).hostname,topLevel=host.match(/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i);return topLevel?topLevel[0]:host}});require.register("visionmedia-debug/index.js",function(exports,require,module){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}});require.register("visionmedia-debug/debug.js",function(exports,require,module){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){}});require.register("yields-prevent/index.js",function(exports,require,module){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}});require.register("analytics/lib/index.js",function(exports,require,module){var Analytics=require("./analytics");var createIntegration=require("integration");var each=require("each");var Integrations=require("integrations");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION="1.3.7";each(Integrations,function(name,Integration){analytics.use(Integration)})});require.register("analytics/lib/analytics.js",function(exports,require,module){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;module.exports=Analytics;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;this._integrations={};user.load();group.load();var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});var ready=after(size(settings),function(){self._readied=true;self.emit("ready")});each(settings,function(name,opts){var Integration=self.Integrations[name];if(options.initialPageview&&opts.initialPageview===false){Integration.prototype.page=after(2,Integration.prototype.page)}var integration=new Integration(clone(opts));integration.once("ready",ready);integration.initialize();self._integrations[name]=integration});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",new Identify({options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",new Group({options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",new Track({properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,url:canonicalUrl(),search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);this._invoke("page",new Page({properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",new Alias({options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(){var canon=canonical();if(canon)return canon;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}});require.register("analytics/lib/cookie.js",function(exports,require,module){var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");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);if(domain===".localhost")domain="";defaults(options,{maxage:31536e6,path:"/",domain:domain});this._options=options};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 });require.register("analytics/lib/entity.js",function(exports,require,module){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options)}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?cookie.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){cookie.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))}});require.register("analytics/lib/group.js",function(exports,require,module){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={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});require.register("analytics/lib/store.js",function(exports,require,module){var bind=require("bind");var defaults=require("defaults");var store=require("store");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});require.register("analytics/lib/user.js",function(exports,require,module){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User});require.register("segmentio-analytics.js-integrations/lib/slugs.json",function(exports,require,module){module.exports=["adroll","adwords","amplitude","awesm","awesomatic","bing-ads","bronto","bugherd","bugsnag","chartbeat","churnbee","clicktale","clicky","comscore","crazy-egg","curebit","customerio","drip","errorception","evergage","facebook-ads","foxmetrics","gauges","get-satisfaction","google-analytics","google-tag-manager","gosquared","heap","hittail","hubspot","improvely","inspectlet","intercom","keen-io","kissmetrics","klaviyo","leadlander","livechat","lucky-orange","lytics","mixpanel","mojn","mouseflow","mousestats","olark","optimizely","perfect-audience","pingdom","preact","qualaroo","quantcast","rollbar","saasquatch","sentry","snapengage","spinnakr","tapstream","trakio","twitter-ads","usercycle","userfox","uservoice","vero","visual-website-optimizer","webengage","woopra","yandex-metrica"]});require.alias("avetisk-defaults/index.js","analytics/deps/defaults/index.js");require.alias("avetisk-defaults/index.js","defaults/index.js");require.alias("component-clone/index.js","analytics/deps/clone/index.js");require.alias("component-clone/index.js","clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-cookie/index.js","analytics/deps/cookie/index.js");require.alias("component-cookie/index.js","cookie/index.js");require.alias("component-each/index.js","analytics/deps/each/index.js");require.alias("component-each/index.js","each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("component-emitter/index.js","analytics/deps/emitter/index.js");require.alias("component-emitter/index.js","emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("component-event/index.js","analytics/deps/event/index.js");require.alias("component-event/index.js","event/index.js");require.alias("component-inherit/index.js","analytics/deps/inherit/index.js");require.alias("component-inherit/index.js","inherit/index.js");require.alias("component-object/index.js","analytics/deps/object/index.js");require.alias("component-object/index.js","object/index.js");require.alias("component-querystring/index.js","analytics/deps/querystring/index.js");require.alias("component-querystring/index.js","querystring/index.js");require.alias("component-trim/index.js","component-querystring/deps/trim/index.js");require.alias("component-url/index.js","analytics/deps/url/index.js");require.alias("component-url/index.js","url/index.js");require.alias("ianstormtaylor-bind/index.js","analytics/deps/bind/index.js");require.alias("ianstormtaylor-bind/index.js","bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","analytics/deps/callback/index.js");require.alias("ianstormtaylor-callback/index.js","callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("ianstormtaylor-is/index.js","analytics/deps/is/index.js");require.alias("ianstormtaylor-is/index.js","is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-after/index.js","analytics/deps/after/index.js");require.alias("segmentio-after/index.js","after/index.js");require.alias("segmentio-analytics.js-integration/lib/index.js","analytics/deps/integration/lib/index.js");require.alias("segmentio-analytics.js-integration/lib/protos.js","analytics/deps/integration/lib/protos.js");require.alias("segmentio-analytics.js-integration/lib/events.js","analytics/deps/integration/lib/events.js");require.alias("segmentio-analytics.js-integration/lib/statics.js","analytics/deps/integration/lib/statics.js");require.alias("segmentio-analytics.js-integration/lib/index.js","analytics/deps/integration/index.js");require.alias("segmentio-analytics.js-integration/lib/index.js","integration/index.js");require.alias("avetisk-defaults/index.js","segmentio-analytics.js-integration/deps/defaults/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integration/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-emitter/index.js","segmentio-analytics.js-integration/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integration/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integration/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("segmentio-after/index.js","segmentio-analytics.js-integration/deps/after/index.js");require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integration/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integration/deps/slug/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integration/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integration/deps/debug/debug.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integration/index.js");require.alias("segmentio-analytics.js-integrations/index.js","analytics/deps/integrations/index.js");require.alias("segmentio-analytics.js-integrations/lib/adroll.js","analytics/deps/integrations/lib/adroll.js");require.alias("segmentio-analytics.js-integrations/lib/adwords.js","analytics/deps/integrations/lib/adwords.js");require.alias("segmentio-analytics.js-integrations/lib/amplitude.js","analytics/deps/integrations/lib/amplitude.js");require.alias("segmentio-analytics.js-integrations/lib/awesm.js","analytics/deps/integrations/lib/awesm.js");require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js","analytics/deps/integrations/lib/awesomatic.js");require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js","analytics/deps/integrations/lib/bing-ads.js");require.alias("segmentio-analytics.js-integrations/lib/bronto.js","analytics/deps/integrations/lib/bronto.js");require.alias("segmentio-analytics.js-integrations/lib/bugherd.js","analytics/deps/integrations/lib/bugherd.js");require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js","analytics/deps/integrations/lib/bugsnag.js");require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js","analytics/deps/integrations/lib/chartbeat.js");require.alias("segmentio-analytics.js-integrations/lib/churnbee.js","analytics/deps/integrations/lib/churnbee.js");require.alias("segmentio-analytics.js-integrations/lib/clicktale.js","analytics/deps/integrations/lib/clicktale.js");require.alias("segmentio-analytics.js-integrations/lib/clicky.js","analytics/deps/integrations/lib/clicky.js");require.alias("segmentio-analytics.js-integrations/lib/comscore.js","analytics/deps/integrations/lib/comscore.js");require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js","analytics/deps/integrations/lib/crazy-egg.js");require.alias("segmentio-analytics.js-integrations/lib/curebit.js","analytics/deps/integrations/lib/curebit.js");require.alias("segmentio-analytics.js-integrations/lib/customerio.js","analytics/deps/integrations/lib/customerio.js");require.alias("segmentio-analytics.js-integrations/lib/drip.js","analytics/deps/integrations/lib/drip.js");require.alias("segmentio-analytics.js-integrations/lib/errorception.js","analytics/deps/integrations/lib/errorception.js");require.alias("segmentio-analytics.js-integrations/lib/evergage.js","analytics/deps/integrations/lib/evergage.js");require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js","analytics/deps/integrations/lib/facebook-ads.js");require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js","analytics/deps/integrations/lib/foxmetrics.js");require.alias("segmentio-analytics.js-integrations/lib/gauges.js","analytics/deps/integrations/lib/gauges.js");require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js","analytics/deps/integrations/lib/get-satisfaction.js");require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js","analytics/deps/integrations/lib/google-analytics.js");require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js","analytics/deps/integrations/lib/google-tag-manager.js");require.alias("segmentio-analytics.js-integrations/lib/gosquared.js","analytics/deps/integrations/lib/gosquared.js");require.alias("segmentio-analytics.js-integrations/lib/heap.js","analytics/deps/integrations/lib/heap.js");require.alias("segmentio-analytics.js-integrations/lib/hittail.js","analytics/deps/integrations/lib/hittail.js");require.alias("segmentio-analytics.js-integrations/lib/hubspot.js","analytics/deps/integrations/lib/hubspot.js");require.alias("segmentio-analytics.js-integrations/lib/improvely.js","analytics/deps/integrations/lib/improvely.js");require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js","analytics/deps/integrations/lib/inspectlet.js");require.alias("segmentio-analytics.js-integrations/lib/intercom.js","analytics/deps/integrations/lib/intercom.js");require.alias("segmentio-analytics.js-integrations/lib/keen-io.js","analytics/deps/integrations/lib/keen-io.js");require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js","analytics/deps/integrations/lib/kissmetrics.js");require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js","analytics/deps/integrations/lib/klaviyo.js");require.alias("segmentio-analytics.js-integrations/lib/leadlander.js","analytics/deps/integrations/lib/leadlander.js");require.alias("segmentio-analytics.js-integrations/lib/livechat.js","analytics/deps/integrations/lib/livechat.js");require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js","analytics/deps/integrations/lib/lucky-orange.js");require.alias("segmentio-analytics.js-integrations/lib/lytics.js","analytics/deps/integrations/lib/lytics.js");require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js","analytics/deps/integrations/lib/mixpanel.js");require.alias("segmentio-analytics.js-integrations/lib/mojn.js","analytics/deps/integrations/lib/mojn.js");require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js","analytics/deps/integrations/lib/mouseflow.js");require.alias("segmentio-analytics.js-integrations/lib/mousestats.js","analytics/deps/integrations/lib/mousestats.js");require.alias("segmentio-analytics.js-integrations/lib/olark.js","analytics/deps/integrations/lib/olark.js");require.alias("segmentio-analytics.js-integrations/lib/optimizely.js","analytics/deps/integrations/lib/optimizely.js");require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js","analytics/deps/integrations/lib/perfect-audience.js");require.alias("segmentio-analytics.js-integrations/lib/pingdom.js","analytics/deps/integrations/lib/pingdom.js");require.alias("segmentio-analytics.js-integrations/lib/preact.js","analytics/deps/integrations/lib/preact.js");require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js","analytics/deps/integrations/lib/qualaroo.js");require.alias("segmentio-analytics.js-integrations/lib/quantcast.js","analytics/deps/integrations/lib/quantcast.js");require.alias("segmentio-analytics.js-integrations/lib/rollbar.js","analytics/deps/integrations/lib/rollbar.js");require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js","analytics/deps/integrations/lib/saasquatch.js");require.alias("segmentio-analytics.js-integrations/lib/sentry.js","analytics/deps/integrations/lib/sentry.js");require.alias("segmentio-analytics.js-integrations/lib/snapengage.js","analytics/deps/integrations/lib/snapengage.js");require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js","analytics/deps/integrations/lib/spinnakr.js");require.alias("segmentio-analytics.js-integrations/lib/tapstream.js","analytics/deps/integrations/lib/tapstream.js");require.alias("segmentio-analytics.js-integrations/lib/trakio.js","analytics/deps/integrations/lib/trakio.js");require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js","analytics/deps/integrations/lib/twitter-ads.js");require.alias("segmentio-analytics.js-integrations/lib/usercycle.js","analytics/deps/integrations/lib/usercycle.js");require.alias("segmentio-analytics.js-integrations/lib/userfox.js","analytics/deps/integrations/lib/userfox.js");require.alias("segmentio-analytics.js-integrations/lib/uservoice.js","analytics/deps/integrations/lib/uservoice.js");require.alias("segmentio-analytics.js-integrations/lib/vero.js","analytics/deps/integrations/lib/vero.js");require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js","analytics/deps/integrations/lib/visual-website-optimizer.js");require.alias("segmentio-analytics.js-integrations/lib/webengage.js","analytics/deps/integrations/lib/webengage.js");require.alias("segmentio-analytics.js-integrations/lib/woopra.js","analytics/deps/integrations/lib/woopra.js");require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js","analytics/deps/integrations/lib/yandex-metrica.js");require.alias("segmentio-analytics.js-integrations/index.js","integrations/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integrations/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-domify/index.js","segmentio-analytics.js-integrations/deps/domify/index.js");require.alias("component-each/index.js","segmentio-analytics.js-integrations/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("component-once/index.js","segmentio-analytics.js-integrations/deps/once/index.js");require.alias("component-type/index.js","segmentio-analytics.js-integrations/deps/type/index.js");require.alias("component-url/index.js","segmentio-analytics.js-integrations/deps/url/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integrations/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integrations/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-analytics.js-integrations/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-alias/index.js","segmentio-analytics.js-integrations/deps/alias/index.js");require.alias("component-clone/index.js","segmentio-alias/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-type/index.js","segmentio-alias/deps/type/index.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integrations/deps/integration/lib/index.js");require.alias("segmentio-analytics.js-integration/lib/protos.js","segmentio-analytics.js-integrations/deps/integration/lib/protos.js");require.alias("segmentio-analytics.js-integration/lib/events.js","segmentio-analytics.js-integrations/deps/integration/lib/events.js");require.alias("segmentio-analytics.js-integration/lib/statics.js","segmentio-analytics.js-integrations/deps/integration/lib/statics.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integrations/deps/integration/index.js");require.alias("avetisk-defaults/index.js","segmentio-analytics.js-integration/deps/defaults/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integration/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-emitter/index.js","segmentio-analytics.js-integration/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integration/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integration/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("segmentio-after/index.js","segmentio-analytics.js-integration/deps/after/index.js");require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integration/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integration/deps/slug/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integration/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integration/deps/debug/debug.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integration/index.js");require.alias("segmentio-canonical/index.js","segmentio-analytics.js-integrations/deps/canonical/index.js");require.alias("segmentio-convert-dates/index.js","segmentio-analytics.js-integrations/deps/convert-dates/index.js");require.alias("component-clone/index.js","segmentio-convert-dates/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-convert-dates/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-extend/index.js","segmentio-analytics.js-integrations/deps/extend/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-analytics.js-integrations/deps/facade/lib/index.js");require.alias("segmentio-facade/lib/alias.js","segmentio-analytics.js-integrations/deps/facade/lib/alias.js");require.alias("segmentio-facade/lib/facade.js","segmentio-analytics.js-integrations/deps/facade/lib/facade.js");require.alias("segmentio-facade/lib/group.js","segmentio-analytics.js-integrations/deps/facade/lib/group.js");require.alias("segmentio-facade/lib/page.js","segmentio-analytics.js-integrations/deps/facade/lib/page.js");require.alias("segmentio-facade/lib/identify.js","segmentio-analytics.js-integrations/deps/facade/lib/identify.js");require.alias("segmentio-facade/lib/is-enabled.js","segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js");require.alias("segmentio-facade/lib/track.js","segmentio-analytics.js-integrations/deps/facade/lib/track.js");require.alias("segmentio-facade/lib/index.js","segmentio-analytics.js-integrations/deps/facade/index.js");require.alias("camshaft-require-component/index.js","segmentio-facade/deps/require-component/index.js");require.alias("segmentio-isodate-traverse/index.js","segmentio-facade/deps/isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("component-clone/index.js","segmentio-facade/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-inherit/index.js","segmentio-facade/deps/inherit/index.js");require.alias("component-trim/index.js","segmentio-facade/deps/trim/index.js");require.alias("segmentio-is-email/index.js","segmentio-facade/deps/is-email/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","segmentio-facade/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","segmentio-facade/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/lib/index.js");require.alias("ianstormtaylor-case/lib/cases.js","segmentio-obj-case/deps/case/lib/cases.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/index.js");require.alias("ianstormtaylor-to-camel-case/index.js","ianstormtaylor-case/deps/to-camel-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-camel-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-constant-case/index.js","ianstormtaylor-case/deps/to-constant-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-dot-case/index.js","ianstormtaylor-case/deps/to-dot-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-dot-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-pascal-case/index.js","ianstormtaylor-case/deps/to-pascal-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-sentence-case/index.js","ianstormtaylor-case/deps/to-sentence-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-slug-case/index.js","ianstormtaylor-case/deps/to-slug-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-slug-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-title-case/index.js","ianstormtaylor-case/deps/to-title-case/index.js");require.alias("component-escape-regexp/index.js","ianstormtaylor-to-title-case/deps/escape-regexp/index.js");require.alias("ianstormtaylor-map/index.js","ianstormtaylor-to-title-case/deps/map/index.js");require.alias("component-each/index.js","ianstormtaylor-map/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-title-case-minors/index.js","ianstormtaylor-to-title-case/deps/title-case-minors/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-to-title-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","ianstormtaylor-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-obj-case/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-facade/index.js");require.alias("segmentio-global-queue/index.js","segmentio-analytics.js-integrations/deps/global-queue/index.js");require.alias("segmentio-is-email/index.js","segmentio-analytics.js-integrations/deps/is-email/index.js");require.alias("segmentio-load-date/index.js","segmentio-analytics.js-integrations/deps/load-date/index.js");require.alias("segmentio-load-script/index.js","segmentio-analytics.js-integrations/deps/load-script/index.js");require.alias("component-type/index.js","segmentio-load-script/deps/type/index.js");require.alias("segmentio-on-body/index.js","segmentio-analytics.js-integrations/deps/on-body/index.js");require.alias("component-each/index.js","segmentio-on-body/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("segmentio-on-error/index.js","segmentio-analytics.js-integrations/deps/on-error/index.js");require.alias("segmentio-to-iso-string/index.js","segmentio-analytics.js-integrations/deps/to-iso-string/index.js");require.alias("segmentio-to-unix-timestamp/index.js","segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js");require.alias("segmentio-use-https/index.js","segmentio-analytics.js-integrations/deps/use-https/index.js"); require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integrations/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integrations/deps/slug/index.js");require.alias("visionmedia-batch/index.js","segmentio-analytics.js-integrations/deps/batch/index.js");require.alias("component-emitter/index.js","visionmedia-batch/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integrations/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integrations/deps/debug/debug.js");require.alias("segmentio-load-pixel/index.js","segmentio-analytics.js-integrations/deps/load-pixel/index.js");require.alias("segmentio-load-pixel/index.js","segmentio-analytics.js-integrations/deps/load-pixel/index.js");require.alias("component-querystring/index.js","segmentio-load-pixel/deps/querystring/index.js");require.alias("component-trim/index.js","component-querystring/deps/trim/index.js");require.alias("segmentio-substitute/index.js","segmentio-load-pixel/deps/substitute/index.js");require.alias("segmentio-substitute/index.js","segmentio-load-pixel/deps/substitute/index.js");require.alias("segmentio-substitute/index.js","segmentio-substitute/index.js");require.alias("segmentio-load-pixel/index.js","segmentio-load-pixel/index.js");require.alias("segmentio-canonical/index.js","analytics/deps/canonical/index.js");require.alias("segmentio-canonical/index.js","canonical/index.js");require.alias("segmentio-extend/index.js","analytics/deps/extend/index.js");require.alias("segmentio-extend/index.js","extend/index.js");require.alias("segmentio-facade/lib/index.js","analytics/deps/facade/lib/index.js");require.alias("segmentio-facade/lib/alias.js","analytics/deps/facade/lib/alias.js");require.alias("segmentio-facade/lib/facade.js","analytics/deps/facade/lib/facade.js");require.alias("segmentio-facade/lib/group.js","analytics/deps/facade/lib/group.js");require.alias("segmentio-facade/lib/page.js","analytics/deps/facade/lib/page.js");require.alias("segmentio-facade/lib/identify.js","analytics/deps/facade/lib/identify.js");require.alias("segmentio-facade/lib/is-enabled.js","analytics/deps/facade/lib/is-enabled.js");require.alias("segmentio-facade/lib/track.js","analytics/deps/facade/lib/track.js");require.alias("segmentio-facade/lib/index.js","analytics/deps/facade/index.js");require.alias("segmentio-facade/lib/index.js","facade/index.js");require.alias("camshaft-require-component/index.js","segmentio-facade/deps/require-component/index.js");require.alias("segmentio-isodate-traverse/index.js","segmentio-facade/deps/isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("component-clone/index.js","segmentio-facade/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-inherit/index.js","segmentio-facade/deps/inherit/index.js");require.alias("component-trim/index.js","segmentio-facade/deps/trim/index.js");require.alias("segmentio-is-email/index.js","segmentio-facade/deps/is-email/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","segmentio-facade/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","segmentio-facade/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/lib/index.js");require.alias("ianstormtaylor-case/lib/cases.js","segmentio-obj-case/deps/case/lib/cases.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/index.js");require.alias("ianstormtaylor-to-camel-case/index.js","ianstormtaylor-case/deps/to-camel-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-camel-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-constant-case/index.js","ianstormtaylor-case/deps/to-constant-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-dot-case/index.js","ianstormtaylor-case/deps/to-dot-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-dot-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-pascal-case/index.js","ianstormtaylor-case/deps/to-pascal-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-sentence-case/index.js","ianstormtaylor-case/deps/to-sentence-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-slug-case/index.js","ianstormtaylor-case/deps/to-slug-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-slug-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-title-case/index.js","ianstormtaylor-case/deps/to-title-case/index.js");require.alias("component-escape-regexp/index.js","ianstormtaylor-to-title-case/deps/escape-regexp/index.js");require.alias("ianstormtaylor-map/index.js","ianstormtaylor-to-title-case/deps/map/index.js");require.alias("component-each/index.js","ianstormtaylor-map/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-title-case-minors/index.js","ianstormtaylor-to-title-case/deps/title-case-minors/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-to-title-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","ianstormtaylor-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-obj-case/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-facade/index.js");require.alias("segmentio-is-email/index.js","analytics/deps/is-email/index.js");require.alias("segmentio-is-email/index.js","is-email/index.js");require.alias("segmentio-is-meta/index.js","analytics/deps/is-meta/index.js");require.alias("segmentio-is-meta/index.js","is-meta/index.js");require.alias("segmentio-isodate-traverse/index.js","analytics/deps/isodate-traverse/index.js");require.alias("segmentio-isodate-traverse/index.js","isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("segmentio-json/index.js","analytics/deps/json/index.js");require.alias("segmentio-json/index.js","json/index.js");require.alias("component-json-fallback/index.js","segmentio-json/deps/json-fallback/index.js");require.alias("segmentio-new-date/lib/index.js","analytics/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","analytics/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","analytics/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","analytics/deps/new-date/index.js");require.alias("segmentio-new-date/lib/index.js","new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/store.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/index.js");require.alias("segmentio-store.js/store.js","store/index.js");require.alias("segmentio-store.js/store.js","segmentio-store.js/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","top-domain/index.js");require.alias("component-url/index.js","segmentio-top-domain/deps/url/index.js");require.alias("segmentio-top-domain/index.js","segmentio-top-domain/index.js");require.alias("visionmedia-debug/index.js","analytics/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","analytics/deps/debug/debug.js");require.alias("visionmedia-debug/index.js","debug/index.js");require.alias("yields-prevent/index.js","analytics/deps/prevent/index.js");require.alias("yields-prevent/index.js","prevent/index.js");require.alias("analytics/lib/index.js","analytics/index.js");if(typeof exports=="object"){module.exports=require("analytics")}else if(typeof define=="function"&&define.amd){define([],function(){return require("analytics")})}else{this["analytics"]=require("analytics")}})();
src/routes.js
tvarner/PortfolioApp
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import Application from './app/app'; import MainViewContainer from './app/components/pages/MainView/MainViewContainer'; import AboutPage from './app/components/pages/AboutPage/AboutPage'; // eslint-disable-line import/no-named-as-default import NotFoundPage from './app/components/pages/NotFound/NotFoundPage'; export default ( <Route path="/" component={Application}> <IndexRoute component={MainViewContainer}/> <Route path="about" component={AboutPage}/> <Route path="*" component={NotFoundPage}/> </Route> );
src/BezierCurve.js
ottoman/bezier-curve
import React, { Component } from 'react'; import d3 from 'd3'; import colors from './colors'; class BezierCurve extends Component { renderXAxis(xMarkerLocations) { let {scale, height} = this.props; // create path data for vertical grid lines at each marker location let createPathData = d3.svg.line().x(scale.x).y(height + 10) .interpolate((points) => points.join(` V ${-10} M `) ); let xPathData = createPathData(xMarkerLocations) + 'V 0'; return ( <path d={xPathData} /> ); } renderYAxis(yMarkerLocations) { let {scale, width} = this.props; // create path data for horizontal grid lines at each marker location let createPathData = d3.svg.line().x(width + 10).y(scale.y) .interpolate((points) => points.join(` H ${-10} M `) ); let yPathData = createPathData(yMarkerLocations) + 'H 0'; return ( <path d={yPathData} /> ); } renderXLabels(xMarkerLocations) { let {scale, height} = this.props; let renderLabel = (anchor, item, index) => <text className="graph-label" key={index} textAnchor="middle" transform={`translate(${scale.x(item)}, 36)`}> {Math.round(item * 100, 2) + '%'} </text> return ( <g> <g transform={`translate(0, ${height})`}> {xMarkerLocations.map(renderLabel.bind(this, 'middle'))} </g> </g> ); } renderYLabels(yMarkerLocations) { let {width, height, scale} = this.props; // render y axis label let renderLabel = (anchor, item, index) => <text className="graph-label" key={index} textAnchor={anchor} transform={`translate(0, ${scale.y(item) + 6})`}> {Math.round(item * 100, 2) + '%'} </text> return ( <g> <g transform={`translate(-26, 0)`}> {yMarkerLocations.map(renderLabel.bind(this, 'end'))} </g> <g transform={`translate(${width + 26}, 0)`}> {yMarkerLocations.map(renderLabel.bind(this, 'start'))} </g> </g> ); } render() { let {width, height, scale} = this.props; // use d3 to calculate x and y axis tick locations let skipStartAndEnd = (value) => value !== 0.0 && value !== 1.0; let yAxis = d3.svg.axis().scale(scale.y).orient('left').ticks(5); let yMarkerLocations = yAxis.scale().ticks(yAxis.ticks()).filter(skipStartAndEnd); let xAxis = d3.svg.axis().scale(scale.x).orient('bottom').ticks(5); let xMarkerLocations = xAxis.scale().ticks(xAxis.ticks()).filter(skipStartAndEnd); return ( <g> {/* background gradient */} <rect fill="url(#chartBG)" width={width} height={height} stroke={colors.graphBGLines} /> {/* background gridlines */} <g stroke={colors.graphBGLines}> {this.renderXAxis(xMarkerLocations)} {this.renderYAxis(yMarkerLocations)} </g> <g clipPath="url(#graph)"> {/* bezier curve background */} <path d={this.props.closedBezierPath} fill="url(#bezierBG)"/> {/* grid lines inside bezier curve */} <g clipPath="url(#closedBezierPath)" stroke="url(#bezierBGLines)"> {this.renderXAxis(xMarkerLocations)} {this.renderYAxis(yMarkerLocations)} </g> {/* the bezier curve */} <path d={this.props.bezierPath} fill="none" stroke={colors.curve} strokeWidth="3" /> </g> {/* labels along both axys */} <g fontSize="17" fill="#aaa"> {this.renderXLabels(xMarkerLocations)} {this.renderYLabels(yMarkerLocations)} </g> </g> ); } } export default BezierCurve;
src/components/smart/CategoriesContainer/CategoriesContainer.js
arfianadam/react-swapi
import React from 'react' import styles from './CategoriesContainer.scss' import Categories from '../../dumb/Categories' class CategoriesContainer extends React.Component { constructor(props) { super(props) this.state = { categories: [ 'films', 'people', 'planets', 'species', 'starships', 'vehicles' ] } } render() { return ( <div className={ styles.CategoriesContainer }> <Categories data={ this.state.categories }/> </div> ) } } export default CategoriesContainer
RNPublisherBanner.js
wkrause13/react-native-admob
import React, { Component } from 'react'; import { requireNativeComponent, UIManager, findNodeHandle, ViewPropTypes, } from 'react-native'; import { string, func, arrayOf } from 'prop-types'; import { createErrorFromErrorData } from './utils'; class PublisherBanner extends Component { constructor() { super(); this.handleSizeChange = this.handleSizeChange.bind(this); this.handleAppEvent = this.handleAppEvent.bind(this); this.handleAdFailedToLoad = this.handleAdFailedToLoad.bind(this); this.state = { style: {}, }; } componentDidMount() { this.loadBanner(); } loadBanner() { UIManager.dispatchViewManagerCommand( findNodeHandle(this._bannerView), UIManager.RNDFPBannerView.Commands.loadBanner, null, ); } handleSizeChange(event) { const { height, width } = event.nativeEvent; this.setState({ style: { width, height } }); if (this.props.onSizeChange) { this.props.onSizeChange({ width, height }); } } handleAppEvent(event) { if (this.props.onAppEvent) { const { name, info } = event.nativeEvent; this.props.onAppEvent({ name, info }); } } handleAdFailedToLoad(event) { if (this.props.onAdFailedToLoad) { this.props.onAdFailedToLoad(createErrorFromErrorData(event.nativeEvent.error)); } } render() { return ( <RNDFPBannerView {...this.props} style={[this.props.style, this.state.style]} onSizeChange={this.handleSizeChange} onAdFailedToLoad={this.handleAdFailedToLoad} onAppEvent={this.handleAppEvent} ref={el => (this._bannerView = el)} /> ); } } Object.defineProperty(PublisherBanner, 'simulatorId', { get() { return UIManager.RNDFPBannerView.Constants.simulatorId; }, }); PublisherBanner.propTypes = { ...ViewPropTypes, /** * DFP iOS library banner size constants * (https://developers.google.com/admob/ios/banner) * banner (320x50, Standard Banner for Phones and Tablets) * largeBanner (320x100, Large Banner for Phones and Tablets) * mediumRectangle (300x250, IAB Medium Rectangle for Phones and Tablets) * fullBanner (468x60, IAB Full-Size Banner for Tablets) * leaderboard (728x90, IAB Leaderboard for Tablets) * smartBannerPortrait (Screen width x 32|50|90, Smart Banner for Phones and Tablets) * smartBannerLandscape (Screen width x 32|50|90, Smart Banner for Phones and Tablets) * * banner is default */ adSize: string, /** * Optional array specifying all valid sizes that are appropriate for this slot. */ validAdSizes: arrayOf(string), /** * DFP ad unit ID */ adUnitID: string, /** * Array of test devices. Use PublisherBanner.simulatorId for the simulator */ testDevices: arrayOf(string), onSizeChange: func, /** * DFP library events */ onAdLoaded: func, onAdFailedToLoad: func, onAdOpened: func, onAdClosed: func, onAdLeftApplication: func, onAppEvent: func, }; const RNDFPBannerView = requireNativeComponent('RNDFPBannerView', PublisherBanner); export default PublisherBanner;
my_elements/highcharts-element/Highcharts-4.0.4/exporting-server/java/highcharts-export/highcharts-export-web/target/highcharts-export-web/resources/lib/jquery-1.11.0.min.js
chuycepeda/polymer-elements
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
src/shared/state/modules/order.js
AlekseyWW/shop-react-ssr
import React from 'react'; import axios from 'axios'; import { post, getAccessToken } from 'utils/api'; import { actions } from './modal'; import { push } from 'react-router-redux'; import ModalExample from '../../components/ModalExample'; export const FETCH_ORDER_REQUEST = '@ORDER/FETCH_ORDER_REQUEST'; export const FETCH_ORDER_SUCCESS = '@ORDER/FETCH_ORDER_SUCCESS'; export const FETCH_ORDER_FAILURE = '@ORDER/FETCH_ORDER_FAILURE'; export function requestOrderStart() { return { type: FETCH_ORDER_REQUEST }; } export function requestOrderDone(data, redirect) { return dispatch => { // dispatch(actions.openModal({ // modalType: ModalExample, // modalProps: { // title: `Заказ ${data.id}`, // status: 'order', // text: ( // <ul> // <li> // <span>E-mail: {data.email}</span> // <span>Телефон: {data.phone}</span> // </li> // <li> // <span>Имя: {data.firstName}</span> // <span>Фамилия: {data.firstName}</span> // </li> // <li> // <span>Адрес: {data.city.name}, {data.address}, {data.aprtaments}, {data.postIndex}</span> // </li> // <li> // <span> Коментарий: {data.comment}</span> // </li> // <li> // <span>Сумма заказа: {data.sum} Р</span> // </li> // </ul> // ), // subTitle: '', // hasClose: true, // // confirm: true, // buttons: [ // { // text: 'Перейти к оплате', // intent: 'success', // onClick: () => { // const url = `http://test-api-shop.abo-soft.com/payment-url/order/${data.id}` // axios({ // method: 'get', // url, // }) // .then(res => { // const { data } = res; // if (typeof data === 'string') { // window.location = data // } // }) // .catch(err => { // console.log(err.message); // }); // } // } // ] // } // })); if (redirect) { dispatch(push('/checkout')); } dispatch({ type: FETCH_ORDER_SUCCESS, payload: data, }); }; } export function requestOrderFail(err) { return { type: FETCH_ORDER_FAILURE, error: err, }; } export const fetchOrder = (data, redirect=true) => { return dispatch => { dispatch(requestOrderStart()); const url = getAccessToken() ? `/users/${getAccessToken()}/orders` : '/orders'; return post( url, data, response => dispatch(requestOrderDone(response, redirect)), error => dispatch(requestOrderFail(error.message)) ); }; }; const initialState = { order: undefined, isFetching: false, error: null, }; export default function postsReducer(state = initialState, action) { switch (action.type) { case FETCH_ORDER_REQUEST: return { ...state, isFetching: true, }; case FETCH_ORDER_SUCCESS: localStorage.setItem("order", JSON.stringify(action.payload)); return { ...state, isFetching: false, order: action.payload, }; case FETCH_ORDER_FAILURE: return { ...state, isFetching: false, order: undefined, error: action.error, }; default: return state; } }
src/Components/ObjectSample/ObjectSample.js
apiaryio/attributes-kit
import React from 'react'; import PropTypes from 'prop-types'; import Radium from 'radium'; import merge from 'lodash/merge'; import { Value } from '../Value/Value'; import Column from '../Column/Column'; import Row from '../Row/Row'; import SampleToggle from '../SampleToggle/SampleToggle'; @Radium class ObjectSample extends React.Component { static propTypes = { element: PropTypes.object, sample: PropTypes.object, sampleIndex: PropTypes.number, samples: PropTypes.array, style: PropTypes.object, collapseByDefault: PropTypes.bool, }; static contextTypes = { theme: PropTypes.object, }; constructor(props) { super(props); this.state = { isExpanded: false, }; } handleExpandCollapse = () => { this.setState({ isExpanded: !this.state.isExpanded, }); }; get style() { const { BORDER_COLOR } = this.context.theme; const style = { header: { borderTop: `1px solid ${BORDER_COLOR}`, paddingTop: '8px', paddingBottom: '8px', paddingLeft: '8px', paddingRight: '8px', }, valueContainer: { paddingLeft: '14px', paddingRight: '14px', }, }; const isLastObjectSample = this.props.sampleIndex === (this.props.samples.length - 1); if (this.state.isExpanded || isLastObjectSample) { style.header.borderBottom = `1px solid ${BORDER_COLOR}`; } return merge(style, this.props.style || {}); } render() { return ( <Row> <Column> <Row style={this.style.header} onClick={this.handleExpandCollapse} > <SampleToggle isExpanded={this.state.isExpanded} onClick={this.handleExpandCollapse} /> </Row> { this.state.isExpanded && <Row style={this.style.valueContainer}> <Value element={this.props.sample} isSample collapseByDefault={this.props.collapseByDefault} /> </Row> } </Column> </Row> ); } } export default ObjectSample;
site/examples/FilterExample.js
ianobermiller/fixed-data-table
"use strict"; var ExampleImage = require('./ExampleImage'); var FakeObjectDataListStore = require('./FakeObjectDataListStore'); var FixedDataTable = require('fixed-data-table'); var React = require('react'); var Column = FixedDataTable.Column; var PropTypes = React.PropTypes; var Table = FixedDataTable.Table; function renderImage(/*string*/ cellData) { return <ExampleImage src={cellData} />; } var FilterExample = React.createClass({ getInitialState() { return { rows : new FakeObjectDataListStore().getAll(), filteredRows: null, filterBy: null }; }, componentWillMount() { this._filterRowsBy(this.state.filterBy); }, _filterRowsBy(filterBy) { var rows = this.state.rows.slice(); var filteredRows = filterBy ? rows.filter(function(row){ return row['firstName'].toLowerCase().indexOf(filterBy.toLowerCase()) >= 0 }) : rows; this.setState({ filteredRows, filterBy, }) }, _rowGetter(rowIndex) { return this.state.filteredRows[rowIndex]; }, _onFilterChange(e) { this._filterRowsBy(e.target.value); }, render() { return ( <div> <input onChange={this._onFilterChange} placeholder='Filter by First Name' /> <br /> <Table rowHeight={50} rowGetter={this._rowGetter} rowsCount={this.state.filteredRows.length} width={this.props.tableWidth} height={this.props.tableHeight} scrollTop={this.props.top} scrollLeft={this.props.left} headerHeight={50}> <Column cellRenderer={renderImage} dataKey='avartar' fixed={true} label='' width={50} /> <Column dataKey='firstName' fixed={true} label='First Name' width={100} /> <Column dataKey='lastName' fixed={true} label='Last Name' width={100} /> <Column dataKey='city' label='City' width={100} /> <Column label='Street' width={200} dataKey='street' /> <Column label='Zip Code' width={200} dataKey='zipCode' /> </Table> </div> ) }, }) module.exports = FilterExample;
src/svg-icons/action/view-list.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewList = (props) => ( <SvgIcon {...props}> <path d="M4 14h4v-4H4v4zm0 5h4v-4H4v4zM4 9h4V5H4v4zm5 5h12v-4H9v4zm0 5h12v-4H9v4zM9 5v4h12V5H9z"/> </SvgIcon> ); ActionViewList = pure(ActionViewList); ActionViewList.displayName = 'ActionViewList'; export default ActionViewList;
src/components/Settings/SharingOptions.js
TheTorProject/ooni-wui
import React from 'react' import { FormattedMessage } from 'react-intl' import Toggle from 'react-toggle' const SharingOptions = ({ onSettingsChange, settings }) => { return ( <div className='row text-xs-center'> <div className='five-cols-md col-xs-6'> <h6> <FormattedMessage id='settings.sharingOptions.uploadMethod' defaultMessage='How should we upload your results?' /> </h6> <i className='medium-icon fa fa-upload' /> <div className='row'> <select onChange={onSettingsChange('uploadMethod')}> <option value='onion'> <FormattedMessage id='settings.sharingOptions.uploadMethod.torHiddenService' defaultMessage='Tor Hidden Service' /> </option> <option value='https'>HTTPS</option> <option value='cloudfront'>Cloudfront</option> </select> </div> </div> <div className='five-cols-md col-xs-6'> <h6> <FormattedMessage id='settings.sharingOptions.includeNetwork' defaultMessage='Include your network information?' /> </h6> <i className='medium-icon fa fa-server' /> <div className='row'> <Toggle defaultChecked={settings.includeNetwork} onChange={onSettingsChange('includeNetwork')} /> </div> </div> <div className='five-cols-md col-xs-6'> <h6> <FormattedMessage id='settings.sharingOptions.includeCountry' defaultMessage='Include your country name?' /> </h6> <i className='medium-icon fa fa-globe' /> <div className='row'> <Toggle defaultChecked={settings.includeCountry} onChange={onSettingsChange('includeCountry')} /> </div> </div> <div className='five-cols-md col-xs-6'> <h6> <FormattedMessage id='settings.sharingOptions.sharePublicly' defaultMessage='Share results publicly?' /> </h6> <i className='medium-icon fa fa-share-square-o' /> <div className='row'> <Toggle defaultChecked={settings.shareResults} onChange={onSettingsChange('shareResults')} /> </div> </div> <div className='five-cols-md col-xs-6'> <h6> <FormattedMessage id='settings.sharingOptions.includeIP' defaultMessage='Include your IP?' /> </h6> <i className='medium-icon fa fa-cube' /> <div className='row'> <Toggle defaultChecked={settings.includeIP} onChange={onSettingsChange('includeIP')} /> </div> </div> </div> ) } SharingOptions.propTypes = { onSettingsChange: React.PropTypes.func, settings: React.PropTypes.object } export default SharingOptions
ajax/libs/jquery-mobile/1.4.1/jquery.mobile.js
gaearon/cdnjs
/*! * jQuery Mobile 1.4.1 * Git HEAD hash: 18c1e32bfc4e0e92756dedc105d799131607f5bb <> Date: Wed Feb 12 2014 22:15:20 UTC * http://jquerymobile.com * * Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license. * http://jquery.org/license * */ (function ( root, doc, factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], function ( $ ) { factory( $, root, doc ); return $.mobile; }); } else { // Browser globals factory( root.jQuery, root, doc ); } }( this, document, function ( jQuery, window, document, undefined ) { (function( $ ) { $.mobile = {}; }( jQuery )); (function( $, window, undefined ) { $.extend( $.mobile, { // Version of the jQuery Mobile Framework version: "1.4.1", // Deprecated and no longer used in 1.4 remove in 1.5 // Define the url parameter used for referencing widget-generated sub-pages. // Translates to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", hideUrlBar: true, // Keepnative Selector keepNative: ":jqmData(role='none'), :jqmData(role='nojs')", // Deprecated in 1.4 remove in 1.5 // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Deprecated in 1.4 remove in 1.5 // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Deprecated in 1.4 remove in 1.5 // Class used for "focus" form element state, from CSS framework focusClass: "ui-focus", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // disable to prevent jquery from bothering with links linkBindingEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "fade", // Set maximum window width for transitions to apply - 'false' for no limit maxTransitionWidth: false, // Minimum scroll distance that will be remembered when returning to a page // Deprecated remove in 1.5 minScrollBack: 0, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", // For error messages, which theme does the box uses? pageLoadErrorMessageTheme: "a", // replace calls to window.history.back with phonegaps navigation helper // where it is provided on the window object phonegapNavigationEnabled: false, //automatically initialize the DOM when it's ready autoInitializePage: true, pushStateEnabled: true, // allows users to opt in to ignoring content by marking a parent element as // data-ignored ignoreContentEnabled: false, buttonMarkup: { hoverDelay: 200 }, // disable the alteration of the dynamic base tag or links in the case // that a dynamic base tag isn't supported dynamicBaseEnabled: true, // default the property to remove dependency on assignment in init module pageContainer: $(), //enable cross-domain page support allowCrossDomainPages: false, dialogHashKey: "&ui-state=dialog" }); })( jQuery, this ); (function( $, window, undefined ) { var nsNormalizeDict = {}, oldFind = $.find, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, jqmDataRE = /:jqmData\(([^)]*)\)/g; $.extend( $.mobile, { // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Retrieve an attribute from an element and perform some massaging of the value getAttribute: function( element, key ) { var data; element = element.jquery ? element[0] : element; if ( element && element.getAttribute ) { data = element.getAttribute( "data-" + $.mobile.ns + key ); } // Copied from core's src/data.js:dataAttr() // Convert from a string to a proper data type 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 ) ? JSON.parse( data ) : data; } catch( err ) {} return data; }, // Expose our cache for testing purposes. nsNormalizeDict: nsNormalizeDict, // Take a data attribute property, prepend the namespace // and then camel case the attribute string. Add the result // to our nsNormalizeDict so we don't have to do this again. nsNormalize: function( prop ) { return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) ); }, // Find the closest javascript page element to gather settings data jsperf test // http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit // possibly naive, but it shows that the parsing overhead for *just* the page selector vs // the page and dialog selector is negligable. This could probably be speed up by // doing a similar parent node traversal to the one found in the inherited theme code above closestPageData: function( $target ) { return $target .closest( ":jqmData(role='page'), :jqmData(role='dialog')" ) .data( "mobile-page" ); } }); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { var result; if ( typeof prop !== "undefined" ) { if ( prop ) { prop = $.mobile.nsNormalize( prop ); } // undefined is permitted as an explicit input for the second param // in this case it returns the value and does not set it to undefined if ( arguments.length < 2 || value === undefined ) { result = this.data( prop ); } else { result = this.data( prop, value ); } } return result; }; $.jqmData = function( elem, prop, value ) { var result; if ( typeof prop !== "undefined" ) { result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value ); } return result; }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.find = function( selector, context, ret, extra ) { if ( selector.indexOf( ":jqmData" ) > -1 ) { selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" ); } return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); })( jQuery, this ); /*! * jQuery UI Core c0ab71056b936627e8a7821f03c044aec6280a40 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "c0ab71056b936627e8a7821f03c044aec6280a40", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return ( /fixed/ ).test( this.css( "position") ) || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; })( jQuery ); (function( $, window, undefined ) { $.extend( $.mobile, { // define the window and the document objects window: $( window ), document: $( document ), // TODO: Remove and use $.ui.keyCode directly keyCode: $.ui.keyCode, // Place to store various widget extensions behaviors: {}, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout(function() { window.scrollTo( 0, ypos ); $.mobile.document.trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, getClosestBaseUrl: function( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = $.mobile.path.documentBase.hrefNoHash; if ( !$.mobile.dynamicBaseEnabled || !url || !$.mobile.path.isPath( url ) ) { url = base; } return $.mobile.path.makeUrlAbsolute( url, base ); }, removeActiveLinkClass: function( forceRemoval ) { if ( !!$.mobile.activeClickedLink && ( !$.mobile.activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) { $.mobile.activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $.mobile.activeClickedLink = null; }, // DEPRECATED in 1.4 // Find the closest parent with a theme class on it. Note that // we are not using $.fn.closest() on purpose here because this // method gets called quite a bit and we need it to be as fast // as possible. getInheritedTheme: function( el, defaultTheme ) { var e = el[ 0 ], ltr = "", re = /ui-(bar|body|overlay)-([a-z])\b/, c, m; while ( e ) { c = e.className || ""; if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) { // We found a parent with a theme class // on it so bail from this loop. break; } e = e.parentNode; } // Return the theme letter we found, if none, return the // specified default. return ltr || defaultTheme || "a"; }, enhanceable: function( elements ) { return this.haveParents( elements, "enhance" ); }, hijackable: function( elements ) { return this.haveParents( elements, "ajax" ); }, haveParents: function( elements, attr ) { if ( !$.mobile.ignoreContentEnabled ) { return elements; } var count = elements.length, $newSet = $(), e, $element, excluded, i, c; for ( i = 0; i < count; i++ ) { $element = elements.eq( i ); excluded = false; e = elements[ i ]; while ( e ) { c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : ""; if ( c === "false" ) { excluded = true; break; } e = e.parentNode; } if ( !excluded ) { $newSet = $newSet.add( $element ); } } return $newSet; }, getScreenHeight: function() { // Native innerHeight returns more accurate value for this across platforms, // jQuery version is here as a normalized fallback for platforms like Symbian return window.innerHeight || $.mobile.window.height(); }, //simply set the active page's minimum height to screen height, depending on orientation resetActivePageHeight: function( height ) { var page = $( "." + $.mobile.activePageClass ), pageHeight = page.height(), pageOuterHeight = page.outerHeight( true ); height = ( typeof height === "number" ) ? height : $.mobile.getScreenHeight(); page.css( "min-height", height - ( pageOuterHeight - pageHeight ) ); }, loading: function() { // If this is the first call to this function, instantiate a loader widget var loader = this.loading._widget || $( $.mobile.loader.prototype.defaultHtml ).loader(), // Call the appropriate method on the loader returnValue = loader.loader.apply( loader, arguments ); // Make sure the loader is retained for future calls to this function. this.loading._widget = loader; return returnValue; } }); $.addDependents = function( elem, newDependents ) { var $elem = $( elem ), dependents = $elem.jqmData( "dependents" ) || $(); $elem.jqmData( "dependents", $( dependents ).add( newDependents ) ); }; // plugins $.fn.extend({ removeWithDependents: function() { $.removeWithDependents( this ); }, // Enhance child elements enhanceWithin: function() { var index, widgetElements = {}, keepNative = $.mobile.page.prototype.keepNativeSelector(), that = this; // Add no js class to elements if ( $.mobile.nojs ) { $.mobile.nojs( this ); } // Bind links for ajax nav if ( $.mobile.links ) { $.mobile.links( this ); } // Degrade inputs for styleing if ( $.mobile.degradeInputsWithin ) { $.mobile.degradeInputsWithin( this ); } // Run buttonmarkup if ( $.fn.buttonMarkup ) { this.find( $.fn.buttonMarkup.initSelector ).not( keepNative ) .jqmEnhanceable().buttonMarkup(); } // Add classes for fieldContain if ( $.fn.fieldcontain ) { this.find( ":jqmData(role='fieldcontain')" ).not( keepNative ) .jqmEnhanceable().fieldcontain(); } // Enhance widgets $.each( $.mobile.widgets, function( name, constructor ) { // If initSelector not false find elements if ( constructor.initSelector ) { // Filter elements that should not be enhanced based on parents var elements = $.mobile.enhanceable( that.find( constructor.initSelector ) ); // If any matching elements remain filter ones with keepNativeSelector if ( elements.length > 0 ) { // $.mobile.page.prototype.keepNativeSelector is deprecated this is just for backcompat // Switch to $.mobile.keepNative in 1.5 which is just a value not a function elements = elements.not( keepNative ); } // Enhance whatever is left if ( elements.length > 0 ) { widgetElements[ constructor.prototype.widgetName ] = elements; } } }); for ( index in widgetElements ) { widgetElements[ index ][ index ](); } return this; }, addDependents: function( newDependents ) { $.addDependents( this, newDependents ); }, // note that this helper doesn't attempt to handle the callback // or setting of an html element's text, its only purpose is // to return the html encoded version of the text in all cases. (thus the name) getEncodedText: function() { return $( "<a>" ).text( this.text() ).html(); }, // fluent helper function for the mobile namespaced equivalent jqmEnhanceable: function() { return $.mobile.enhanceable( this ); }, jqmHijackable: function() { return $.mobile.hijackable( this ); } }); $.removeWithDependents = function( nativeElement ) { var element = $( nativeElement ); ( element.jqmData( "dependents" ) || $() ).remove(); element.remove(); }; $.addDependents = function( nativeElement, newDependents ) { var element = $( nativeElement ), dependents = element.jqmData( "dependents" ) || $(); element.jqmData( "dependents", $( dependents ).add( newDependents ) ); }; $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /*! * jQuery UI Widget c0ab71056b936627e8a7821f03c044aec6280a40 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { var rcapitals = /[A-Z]/g, replaceFunction = function( c ) { return "-" + c.toLowerCase(); }; $.extend( $.Widget.prototype, { _getCreateOptions: function() { var option, value, elem = this.element[ 0 ], options = {}; // if ( !$.mobile.getAttribute( elem, "defaults" ) ) { for ( option in this.options ) { value = $.mobile.getAttribute( elem, option.replace( rcapitals, replaceFunction ) ); if ( value != null ) { options[ option ] = value; } } } return options; } }); //TODO: Remove in 1.5 for backcompat only $.mobile.widget = $.Widget; })( jQuery ); (function( $ ) { // TODO move loader class down into the widget settings var loaderClass = "ui-loader", $html = $( "html" ); $.widget( "mobile.loader", { // NOTE if the global config settings are defined they will override these // options options: { // the theme for the loading message theme: "a", // whether the text in the loading message is shown textVisible: false, // custom html for the inner content of the loading message html: "", // the text to be displayed when the popup is shown text: "loading" }, defaultHtml: "<div class='" + loaderClass + "'>" + "<span class='ui-icon-loading'></span>" + "<h1></h1>" + "</div>", // For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top fakeFixLoader: function() { var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); this.element .css({ top: $.support.scrollTop && this.window.scrollTop() + this.window.height() / 2 || activeBtn.length && activeBtn.offset().top || 100 }); }, // check position of loader to see if it appears to be "fixed" to center // if not, use abs positioning checkLoaderPosition: function() { var offset = this.element.offset(), scrollTop = this.window.scrollTop(), screenHeight = $.mobile.getScreenHeight(); if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) { this.element.addClass( "ui-loader-fakefix" ); this.fakeFixLoader(); this.window .unbind( "scroll", this.checkLoaderPosition ) .bind( "scroll", $.proxy( this.fakeFixLoader, this ) ); } }, resetHtml: function() { this.element.html( $( this.defaultHtml ).html() ); }, // Turn on/off page loading message. Theme doubles as an object argument // with the following shape: { theme: '', text: '', html: '', textVisible: '' } // NOTE that the $.mobile.loading* settings and params past the first are deprecated // TODO sweet jesus we need to break some of this out show: function( theme, msgText, textonly ) { var textVisible, message, loadSettings; this.resetHtml(); // use the prototype options so that people can set them globally at // mobile init. Consistency, it's what's for dinner if ( $.type( theme ) === "object" ) { loadSettings = $.extend( {}, this.options, theme ); theme = loadSettings.theme; } else { loadSettings = this.options; // here we prefer the theme value passed as a string argument, then // we prefer the global option because we can't use undefined default // prototype options, then the prototype option theme = theme || loadSettings.theme; } // set the message text, prefer the param, then the settings object // then loading message message = msgText || ( loadSettings.text === false ? "" : loadSettings.text ); // prepare the dom $html.addClass( "ui-loading" ); textVisible = loadSettings.textVisible; // add the proper css given the options (theme, text, etc) // Force text visibility if the second argument was supplied, or // if the text was explicitly set in the object args this.element.attr("class", loaderClass + " ui-corner-all ui-body-" + theme + " ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) + ( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) ); // TODO verify that jquery.fn.html is ok to use in both cases here // this might be overly defensive in preventing unknowing xss // if the html attribute is defined on the loading settings, use that // otherwise use the fallbacks from above if ( loadSettings.html ) { this.element.html( loadSettings.html ); } else { this.element.find( "h1" ).text( message ); } // attach the loader to the DOM this.element.appendTo( $.mobile.pageContainer ); // check that the loader is visible this.checkLoaderPosition(); // on scroll check the loader position this.window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) ); }, hide: function() { $html.removeClass( "ui-loading" ); if ( this.options.text ) { this.element.removeClass( "ui-loader-fakefix" ); } $.mobile.window.unbind( "scroll", this.fakeFixLoader ); $.mobile.window.unbind( "scroll", this.checkLoaderPosition ); } }); })(jQuery, this); /*! * jQuery hashchange event - v1.3 - 7/21/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv window.attachEvent && !window.addEventListener && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); (function( $, undefined ) { /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia = window.matchMedia || (function( doc, undefined ) { var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement( "body" ), div = doc.createElement( "div" ); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore( fakeBody, refNode ); bool = div.offsetWidth === 42; docElem.removeChild( fakeBody ); return { matches: bool, media: q }; }; }( document )); // $.mobile.media uses matchMedia to return a boolean. $.mobile.media = function( q ) { return window.matchMedia( q ).matches; }; })(jQuery); (function( $, undefined ) { var support = { touch: "ontouchend" in document }; $.mobile.support = $.mobile.support || {}; $.extend( $.support, support ); $.extend( $.mobile.support, support ); }( jQuery )); (function( $, undefined ) { $.extend( $.support, { orientation: "orientation" in window && "onorientationchange" in window }); }( jQuery )); (function( $, undefined ) { // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ), v; for ( v in props ) { if ( fbCSS[ props[ v ] ] !== undefined ) { return true; } } } var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "Webkit", "Moz", "O" ], webos = "palmGetResource" in window, //only used to rule out scrollTop operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]", bb = window.blackberry && !propExists( "-webkit-transform" ), //only used to rule out box shadow, as it's filled opaque on BB 5 and lower nokiaLTE7_3; // inline SVG support test function inlineSVG() { // Thanks Modernizr & Erik Dahlstrom var w = window, svg = !!w.document.createElementNS && !!w.document.createElementNS( "http://www.w3.org/2000/svg", "svg" ).createSVGRect && !( w.opera && navigator.userAgent.indexOf( "Chrome" ) === -1 ), support = function( data ) { if ( !( data && svg ) ) { $( "html" ).addClass( "ui-nosvg" ); } }, img = new w.Image(); img.onerror = function() { support( false ); }; img.onload = function() { support( img.width === 1 && img.height === 1 ); }; img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; } function transform3dTest() { var mqProp = "transform-3d", // Because the `translate3d` test below throws false positives in Android: ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" ), el, transforms, t; if ( ret ) { return !!ret; } el = document.createElement( "div" ); transforms = { // We’re omitting Opera for the time being; MS uses unprefixed. "MozTransform": "-moz-transform", "transform": "transform" }; fakeBody.append( el ); for ( t in transforms ) { if ( el.style[ t ] !== undefined ) { el.style[ t ] = "translate3d( 100px, 1px, 1px )"; ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] ); } } return ( !!ret && ret !== "none" ); } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl' />" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href || location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // Thanks Modernizr function cssPointerEventsTest() { var element = document.createElement( "x" ), documentElement = document.documentElement, getComputedStyle = window.getComputedStyle, supports; if ( !( "pointerEvents" in element.style ) ) { return false; } element.style.pointerEvents = "auto"; element.style.pointerEvents = "x"; documentElement.appendChild( element ); supports = getComputedStyle && getComputedStyle( element, "" ).pointerEvents === "auto"; documentElement.removeChild( element ); return !!supports; } function boundingRect() { var div = document.createElement( "div" ); return typeof div.getBoundingClientRect !== "undefined"; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.extend( $.mobile, { browser: {} } ); $.mobile.browser.oldIE = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; do { div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->"; } while( a[0] ); return v > 4 ? v : !v; })(); function fixedPosition() { var w = window, ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], ffmatch = ua.match( /Fennec\/([0-9]+)/ ), ffversion = !!ffmatch && ffmatch[ 1 ], operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ), omversion = !!operammobilematch && operammobilematch[ 1 ]; if ( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) || // Opera Mini ( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) || ( operammobilematch && omversion < 7458 ) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) ( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) || // Firefox Mobile before 6.0 - ( ffversion && ffversion < 6 ) || // WebOS less than 3 ( "palmGetResource" in window && wkversion && wkversion < 534 ) || // MeeGo ( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) { return false; } return true; } $.extend( $.support, { // Note, Chrome for iOS has an extremely quirky implementation of popstate. // We've chosen to take the shortest path to a bug fix here for issue #5426 // See the following link for information about the regex chosen // https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent pushState: "pushState" in history && "replaceState" in history && // When running inside a FF iframe, calling replaceState causes an error !( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) && ( window.navigator.userAgent.search(/CriOS/) === -1 ), mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), touchOverflow: !!propExists( "overflowScrolling" ), cssTransform3d: transform3dTest(), boxShadow: !!propExists( "boxShadow" ) && !bb, fixedPosition: fixedPosition(), scrollTop: ("pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ]) && !webos && !operamini, dynamicBaseTag: baseTagTest(), cssPointerEvents: cssPointerEventsTest(), boundingRect: boundingRect(), inlineSVG: inlineSVG }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible nokiaLTE7_3 = (function() { var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ $.mobile.gradeA = function() { return ( ( $.support.mediaquery && $.support.cssPseudoElement ) || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 8 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null ); }; $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini operamini || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-noboxshadow" ); } })( jQuery ); (function( $, undefined ) { var $win = $.mobile.window, self, dummyFnToInitNavigate = function() { }; $.event.special.beforenavigate = { setup: function() { $win.on( "navigate", dummyFnToInitNavigate ); }, teardown: function() { $win.off( "navigate", dummyFnToInitNavigate ); } }; $.event.special.navigate = self = { bound: false, pushStateEnabled: true, originalEventName: undefined, // If pushstate support is present and push state support is defined to // be true on the mobile namespace. isPushStateEnabled: function() { return $.support.pushState && $.mobile.pushStateEnabled === true && this.isHashChangeEnabled(); }, // !! assumes mobile namespace is present isHashChangeEnabled: function() { return $.mobile.hashListeningEnabled === true; }, // TODO a lot of duplication between popstate and hashchange popstate: function( event ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ), state = event.originalEvent.state || {}; beforeNavigate.originalEvent = event; $win.trigger( beforeNavigate ); if ( beforeNavigate.isDefaultPrevented() ) { return; } if ( event.historyState ) { $.extend(state, event.historyState); } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // NOTE we let the current stack unwind because any assignment to // location.hash will stop the world and run this event handler. By // doing this we create a similar behavior to hashchange on hash // assignment setTimeout(function() { $win.trigger( newEvent, { state: state }); }, 0); }, hashchange: function( event /*, data */ ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ); beforeNavigate.originalEvent = event; $win.trigger( beforeNavigate ); if ( beforeNavigate.isDefaultPrevented() ) { return; } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // Trigger the hashchange with state provided by the user // that altered the hash $win.trigger( newEvent, { // Users that want to fully normalize the two events // will need to do history management down the stack and // add the state to the event before this binding is fired // TODO consider allowing for the explicit addition of callbacks // to be fired before this value is set to avoid event timing issues state: event.hashchangeState || {} }); }, // TODO We really only want to set this up once // but I'm not clear if there's a beter way to achieve // this with the jQuery special event structure setup: function( /* data, namespaces */ ) { if ( self.bound ) { return; } self.bound = true; if ( self.isPushStateEnabled() ) { self.originalEventName = "popstate"; $win.bind( "popstate.navigate", self.popstate ); } else if ( self.isHashChangeEnabled() ) { self.originalEventName = "hashchange"; $win.bind( "hashchange.navigate", self.hashchange ); } } }; })( jQuery ); (function( $, undefined ) { var path, $base, dialogHashKey = "&ui-state=dialog"; $.mobile.path = path = { uiStateKey: "&ui-state", // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:[email protected]:8080/mail/inbox // [3]: http://jblas:[email protected]:8080 // [4]: http: // [5]: // // [6]: jblas:[email protected]:8080 // [7]: jblas:password // [8]: jblas // [9]: password // [10]: mycompany.com:8080 // [11]: mycompany.com // [12]: 8080 // [13]: /mail/inbox // [14]: /mail/ // [15]: inbox // [16]: ?msg=1234&type=unread // [17]: #msg-content // urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, // Abstraction to address xss (Issue #4787) by removing the authority in // browsers that auto decode it. All references to location.href should be // replaced with a call to this method so that it can be dealt with properly here getLocation: function( url ) { var uri = url ? this.parseUrl( url ) : location, hash = this.parseUrl( url || location.href ).hash; // mimic the browser with an empty string when the hash is empty hash = hash === "#" ? "" : hash; // Make sure to parse the url or the location object for the hash because using location.hash // is autodecoded in firefox, the rest of the url should be from the object (location unless // we're testing) to avoid the inclusion of the authority return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash; }, //return the original document url getDocumentUrl: function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href; }, parseLocation: function() { return this.parseUrl( this.getLocation() ); }, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var matches = path.urlParseRE.exec( url || "" ) || []; // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. return { href: matches[ 0 ] || "", hrefNoHash: matches[ 1 ] || "", hrefNoSearch: matches[ 2 ] || "", domain: matches[ 3 ] || "", protocol: matches[ 4 ] || "", doubleSlash: matches[ 5 ] || "", authority: matches[ 6 ] || "", username: matches[ 8 ] || "", password: matches[ 9 ] || "", host: matches[ 10 ] || "", hostname: matches[ 11 ] || "", port: matches[ 12 ] || "", pathname: matches[ 13 ] || "", directory: matches[ 14 ] || "", filename: matches[ 15 ] || "", search: matches[ 16 ] || "", hash: matches[ 17 ] || "" }; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { var absStack, relStack, i, d; if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; absStack = absPath ? absPath.split( "/" ) : []; relStack = relPath.split( "/" ); for ( i = 0; i < relStack.length; i++ ) { d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } if ( absUrl === undefined ) { absUrl = this.documentBase; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ), authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + doubleSlash + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // and remove otherwise the Data Url won't match the id of the embedded Page. return u.hash .split( dialogHashKey )[0] .replace( /^#/, "" ) .replace( /\?.*$/, "" ); } else if ( path.isSameDomain( u, this.documentBase ) ) { return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0]; } return window.decodeURIComponent(absUrl); }, //get path from current hash, or from a file path get: function( newPath ) { if ( newPath === undefined ) { newPath = path.parseLocation().hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, "" ); }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( this.documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, stripQueryParams: function( url ) { return url.replace( /\?.*$/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, isHashValid: function( hash ) { return ( /^#[^#]+$/ ).test( hash ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== this.documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the this.documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) ); } return ( /^#/ ).test( u.href ); }, squash: function( url, resolutionUrl ) { var href, cleanedUrl, search, stateIndex, isPath = this.isPath( url ), uri = this.parseUrl( url ), preservedHash = uri.hash, uiState = ""; // produce a url against which we can resole the provided path resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl()); // If the url is anything but a simple string, remove any preceding hash // eg #foo/bar -> foo/bar // #foo -> #foo cleanedUrl = isPath ? path.stripHash( url ) : url; // If the url is a full url with a hash check if the parsed hash is a path // if it is, strip the #, and use it otherwise continue without change cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl; // Split the UI State keys off the href stateIndex = cleanedUrl.indexOf( this.uiStateKey ); // store the ui state keys for use if ( stateIndex > -1 ) { uiState = cleanedUrl.slice( stateIndex ); cleanedUrl = cleanedUrl.slice( 0, stateIndex ); } // make the cleanedUrl absolute relative to the resolution url href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl ); // grab the search from the resolved url since parsing from // the passed url may not yield the correct result search = this.parseUrl( href ).search; // TODO all this crap is terrible, clean it up if ( isPath ) { // reject the hash if it's a path or it's just a dialog key if ( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) { preservedHash = ""; } // Append the UI State keys where it exists and it's been removed // from the url if ( uiState && preservedHash.indexOf( this.uiStateKey ) === -1) { preservedHash += uiState; } // make sure that pound is on the front of the hash if ( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ) { preservedHash = "#" + preservedHash; } // reconstruct each of the pieces with the new search string and hash href = path.parseUrl( href ); href = href.protocol + "//" + href.host + href.pathname + search + preservedHash; } else { href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState; } return href; }, isPreservableHash: function( hash ) { return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0; }, // Escape weird characters in the hash if it is to be used as a selector hashToSelector: function( hash ) { var hasHash = ( hash.substring( 0, 1 ) === "#" ); if ( hasHash ) { hash = hash.substring( 1 ); } return ( hasHash ? "#" : "" ) + hash.replace( /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, "\\$1" ); }, // return the substring of a filepath before the sub-page key, for making // a server request getFilePath: function( path ) { var splitkey = "&" + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, // check if the specified url refers to the first page in the main // application document. isFirstPageUrl: function( url ) { // We only deal with absolute paths. var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ), // Does the url have the same path as the document? samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ), // Get the first page element. fp = $.mobile.firstPage, // Get the id of the first page element if it has one. fpId = fp && fp[0] ? fp[0].id : undefined; // The url refers to the first page if the path matches the document and // it either has no hash value, or the hash is exactly equal to the id // of the first page element. return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) ); }, // Some embedded browsers, like the web view in Phone Gap, allow // cross-domain XHR requests if the document doing the request was loaded // via the file:// protocol. This is usually to allow the application to // "phone home" and fetch app specific data. We normally let the browser // handle external/cross-domain urls, but if the allowCrossDomainPages // option is true, we will allow cross-domain http/https requests to go // through our page loading logic. isPermittedCrossDomainRequest: function( docUrl, reqUrl ) { return $.mobile.allowCrossDomainPages && (docUrl.protocol === "file:" || docUrl.protocol === "content:") && reqUrl.search( /^https?:/ ) !== -1; } }; path.documentUrl = path.parseLocation(); $base = $( "head" ).find( "base" ); path.documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) : path.documentUrl; path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash); //return the original document base url path.getDocumentBase = function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href; }; // DEPRECATED as of 1.4.0 - remove in 1.5.0 $.extend( $.mobile, { //return the original document url getDocumentUrl: path.getDocumentUrl, //return the original document base url getDocumentBase: path.getDocumentBase }); })( jQuery ); (function( $, undefined ) { $.mobile.History = function( stack, index ) { this.stack = stack || []; this.activeIndex = index || 0; }; $.extend($.mobile.History.prototype, { getActive: function() { return this.stack[ this.activeIndex ]; }, getLast: function() { return this.stack[ this.previousIndex ]; }, getNext: function() { return this.stack[ this.activeIndex + 1 ]; }, getPrev: function() { return this.stack[ this.activeIndex - 1 ]; }, // addNew is used whenever a new page is added add: function( url, data ) { data = data || {}; //if there's forward history, wipe it if ( this.getNext() ) { this.clearForward(); } // if the hash is included in the data make sure the shape // is consistent for comparison if ( data.hash && data.hash.indexOf( "#" ) === -1) { data.hash = "#" + data.hash; } data.url = url; this.stack.push( data ); this.activeIndex = this.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { this.stack = this.stack.slice( 0, this.activeIndex + 1 ); }, find: function( url, stack, earlyReturn ) { stack = stack || this.stack; var entry, i, length = stack.length, index; for ( i = 0; i < length; i++ ) { entry = stack[i]; if ( decodeURIComponent(url) === decodeURIComponent(entry.url) || decodeURIComponent(url) === decodeURIComponent(entry.hash) ) { index = i; if ( earlyReturn ) { return index; } } } return index; }, closest: function( url ) { var closest, a = this.activeIndex; // First, take the slice of the history stack before the current index and search // for a url match. If one is found, we'll avoid avoid looking through forward history // NOTE the preference for backward history movement is driven by the fact that // most mobile browsers only have a dedicated back button, and users rarely use // the forward button in desktop browser anyhow closest = this.find( url, this.stack.slice(0, a) ); // If nothing was found in backward history check forward. The `true` // value passed as the third parameter causes the find method to break // on the first match in the forward history slice. The starting index // of the slice must then be added to the result to get the element index // in the original history stack :( :( // // TODO this is hyper confusing and should be cleaned up (ugh so bad) if ( closest === undefined ) { closest = this.find( url, this.stack.slice(a), true ); closest = closest === undefined ? closest : closest + a; } return closest; }, direct: function( opts ) { var newActiveIndex = this.closest( opts.url ), a = this.activeIndex; // save new page index, null check to prevent falsey 0 result // record the previous index for reference if ( newActiveIndex !== undefined ) { this.activeIndex = newActiveIndex; this.previousIndex = a; } // invoke callbacks where appropriate // // TODO this is also convoluted and confusing if ( newActiveIndex < a ) { ( opts.present || opts.back || $.noop )( this.getActive(), "back" ); } else if ( newActiveIndex > a ) { ( opts.present || opts.forward || $.noop )( this.getActive(), "forward" ); } else if ( newActiveIndex === undefined && opts.missing ) { opts.missing( this.getActive() ); } } }); })( jQuery ); (function( $, undefined ) { var path = $.mobile.path, initialHref = location.href; $.mobile.Navigator = function( history ) { this.history = history; this.ignoreInitialHashChange = true; $.mobile.window.bind({ "popstate.history": $.proxy( this.popstate, this ), "hashchange.history": $.proxy( this.hashchange, this ) }); }; $.extend($.mobile.Navigator.prototype, { squash: function( url, data ) { var state, href, hash = path.isPath(url) ? path.stripHash(url) : url; href = path.squash( url ); // make sure to provide this information when it isn't explicitly set in the // data object that was passed to the squash method state = $.extend({ hash: hash, url: href }, data); // replace the current url with the new href and store the state // Note that in some cases we might be replacing an url with the // same url. We do this anyways because we need to make sure that // all of our history entries have a state object associated with // them. This allows us to work around the case where $.mobile.back() // is called to transition from an external page to an embedded page. // In that particular case, a hashchange event is *NOT* generated by the browser. // Ensuring each history entry has a state object means that onPopState() // will always trigger our hashchange callback even when a hashchange event // is not fired. window.history.replaceState( state, state.title || document.title, href ); return state; }, hash: function( url, href ) { var parsed, loc, hash, resolved; // Grab the hash for recording. If the passed url is a path // we used the parsed version of the squashed url to reconstruct, // otherwise we assume it's a hash and store it directly parsed = path.parseUrl( url ); loc = path.parseLocation(); if ( loc.pathname + loc.search === parsed.pathname + parsed.search ) { // If the pathname and search of the passed url is identical to the current loc // then we must use the hash. Otherwise there will be no event // eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz" hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search; } else if ( path.isPath(url) ) { resolved = path.parseUrl( href ); // If the passed url is a path, make it domain relative and remove any trailing hash hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : ""); } else { hash = url; } return hash; }, // TODO reconsider name go: function( url, data, noEvents ) { var state, href, hash, popstateEvent, isPopStateEvent = $.event.special.navigate.isPushStateEnabled(); // Get the url as it would look squashed on to the current resolution url href = path.squash( url ); // sort out what the hash sould be from the url hash = this.hash( url, href ); // Here we prevent the next hash change or popstate event from doing any // history management. In the case of hashchange we don't swallow it // if there will be no hashchange fired (since that won't reset the value) // and will swallow the following hashchange if ( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) { this.preventNextHashChange = noEvents; } // IMPORTANT in the case where popstate is supported the event will be triggered // directly, stopping further execution - ie, interupting the flow of this // method call to fire bindings at this expression. Below the navigate method // there is a binding to catch this event and stop its propagation. // // We then trigger a new popstate event on the window with a null state // so that the navigate events can conclude their work properly // // if the url is a path we want to preserve the query params that are available on // the current url. this.preventHashAssignPopState = true; window.location.hash = hash; // If popstate is enabled and the browser triggers `popstate` events when the hash // is set (this often happens immediately in browsers like Chrome), then the // this flag will be set to false already. If it's a browser that does not trigger // a `popstate` on hash assignement or `replaceState` then we need avoid the branch // that swallows the event created by the popstate generated by the hash assignment // At the time of this writing this happens with Opera 12 and some version of IE this.preventHashAssignPopState = false; state = $.extend({ url: href, hash: hash, title: document.title }, data); if ( isPopStateEvent ) { popstateEvent = new $.Event( "popstate" ); popstateEvent.originalEvent = { type: "popstate", state: null }; this.squash( url, state ); // Trigger a new faux popstate event to replace the one that we // caught that was triggered by the hash setting above. if ( !noEvents ) { this.ignorePopState = true; $.mobile.window.trigger( popstateEvent ); } } // record the history entry so that the information can be included // in hashchange event driven navigate events in a similar fashion to // the state that's provided by popstate this.history.add( state.url, state ); }, // This binding is intended to catch the popstate events that are fired // when execution of the `$.navigate` method stops at window.location.hash = url; // and completely prevent them from propagating. The popstate event will then be // retriggered after execution resumes // // TODO grab the original event here and use it for the synthetic event in the // second half of the navigate execution that will follow this binding popstate: function( event ) { var hash, state; // Partly to support our test suite which manually alters the support // value to test hashchange. Partly to prevent all around weirdness if ( !$.event.special.navigate.isPushStateEnabled() ) { return; } // If this is the popstate triggered by the actual alteration of the hash // prevent it completely. History is tracked manually if ( this.preventHashAssignPopState ) { this.preventHashAssignPopState = false; event.stopImmediatePropagation(); return; } // if this is the popstate triggered after the `replaceState` call in the go // method, then simply ignore it. The history entry has already been captured if ( this.ignorePopState ) { this.ignorePopState = false; return; } // If there is no state, and the history stack length is one were // probably getting the page load popstate fired by browsers like chrome // avoid it and set the one time flag to false. // TODO: Do we really need all these conditions? Comparing location hrefs // should be sufficient. if ( !event.originalEvent.state && this.history.stack.length === 1 && this.ignoreInitialHashChange ) { this.ignoreInitialHashChange = false; if ( location.href === initialHref ) { event.preventDefault(); return; } } // account for direct manipulation of the hash. That is, we will receive a popstate // when the hash is changed by assignment, and it won't have a state associated. We // then need to squash the hash. See below for handling of hash assignment that // matches an existing history entry // TODO it might be better to only add to the history stack // when the hash is adjacent to the active history entry hash = path.parseLocation().hash; if ( !event.originalEvent.state && hash ) { // squash the hash that's been assigned on the URL with replaceState // also grab the resulting state object for storage state = this.squash( hash ); // record the new hash as an additional history entry // to match the browser's treatment of hash assignment this.history.add( state.url, state ); // pass the newly created state information // along with the event event.historyState = state; // do not alter history, we've added a new history entry // so we know where we are return; } // If all else fails this is a popstate that comes from the back or forward buttons // make sure to set the state of our history stack properly, and record the directionality this.history.direct({ url: (event.originalEvent.state || {}).url || hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.historyState = $.extend({}, historyEntry); event.historyState.direction = direction; } }); }, // NOTE must bind before `navigate` special event hashchange binding otherwise the // navigation data won't be attached to the hashchange event in time for those // bindings to attach it to the `navigate` special event // TODO add a check here that `hashchange.navigate` is bound already otherwise it's // broken (exception?) hashchange: function( event ) { var history, hash; // If hashchange listening is explicitly disabled or pushstate is supported // avoid making use of the hashchange handler. if (!$.event.special.navigate.isHashChangeEnabled() || $.event.special.navigate.isPushStateEnabled() ) { return; } // On occasion explicitly want to prevent the next hash from propogating because we only // with to alter the url to represent the new state do so here if ( this.preventNextHashChange ) { this.preventNextHashChange = false; event.stopImmediatePropagation(); return; } history = this.history; hash = path.parseLocation().hash; // If this is a hashchange caused by the back or forward button // make sure to set the state of our history stack properly this.history.direct({ url: hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.hashchangeState = $.extend({}, historyEntry); event.hashchangeState.direction = direction; }, // When we don't find a hash in our history clearly we're aiming to go there // record the entry as new for future traversal // // NOTE it's not entirely clear that this is the right thing to do given that we // can't know the users intention. It might be better to explicitly _not_ // support location.hash assignment in preference to $.navigate calls // TODO first arg to add should be the href, but it causes issues in identifying // embeded pages missing: function() { history.add( hash, { hash: hash, title: document.title }); } }); } }); })( jQuery ); (function( $, undefined ) { // TODO consider queueing navigation activity until previous activities have completed // so that end users don't have to think about it. Punting for now // TODO !! move the event bindings into callbacks on the navigate event $.mobile.navigate = function( url, data, noEvents ) { $.mobile.navigate.navigator.go( url, data, noEvents ); }; // expose the history on the navigate method in anticipation of full integration with // existing navigation functionalty that is tightly coupled to the history information $.mobile.navigate.history = new $.mobile.History(); // instantiate an instance of the navigator for use within the $.navigate method $.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history ); var loc = $.mobile.path.parseLocation(); $.mobile.navigate.history.add( loc.href, {hash: loc.hash} ); })( jQuery ); (function( $, undefined ) { var props = { "animation": {}, "transition": {} }, testElement = document.createElement( "a" ), vendorPrefixes = [ "", "webkit-", "moz-", "o-" ]; $.each( [ "animation", "transition" ], function( i, test ) { // Get correct name for test var testName = ( i === 0 ) ? test + "-" + "name" : test; $.each( vendorPrefixes, function( j, prefix ) { if ( testElement.style[ $.camelCase( prefix + testName ) ] !== undefined ) { props[ test ][ "prefix" ] = prefix; return false; } }); // Set event and duration names for later use props[ test ][ "duration" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "duration" ); props[ test ][ "event" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "end" ); // All lower case if not a vendor prop if ( props[ test ][ "prefix" ] === "" ) { props[ test ][ "duration" ] = props[ test ][ "duration" ].toLowerCase(); props[ test ][ "event" ] = props[ test ][ "event" ].toLowerCase(); } }); // If a valid prefix was found then the it is supported by the browser $.support.cssTransitions = ( props[ "transition" ][ "prefix" ] !== undefined ); $.support.cssAnimations = ( props[ "animation" ][ "prefix" ] !== undefined ); // Remove the testElement $( testElement ).remove(); // Animation complete callback $.fn.animationComplete = function( callback, type, fallbackTime ) { var timer, duration, that = this, animationType = ( !type || type === "animation" ) ? "animation" : "transition"; // Make sure selected type is supported by browser if ( ( $.support.cssTransitions && animationType === "transition" ) || ( $.support.cssAnimations && animationType === "animation" ) ) { // If a fallback time was not passed set one if ( fallbackTime === undefined ) { // Make sure the was not bound to document before checking .css if ( $( this ).context !== document ) { // Parse the durration since its in second multiple by 1000 for milliseconds // Multiply by 3 to make sure we give the animation plenty of time. duration = parseFloat( $( this ).css( props[ animationType ].duration ) ) * 3000; } // If we could not read a duration use the default if ( duration === 0 || duration === undefined ) { duration = $.fn.animationComplete.default; } } // Sets up the fallback if event never comes timer = setTimeout( function() { $( that ).off( props[ animationType ].event ); callback.apply( that ); }, duration ); // Bind the event return $( this ).one( props[ animationType ].event, function() { // Clear the timer so we dont call callback twice clearTimeout( timer ); callback.call( this, arguments ); }); } else { // CSS animation / transitions not supported // Defer execution for consistency between webkit/non webkit setTimeout( $.proxy( callback, this ), 0 ); return $( this ); } }; // Allow default callback to be configured on mobileInit $.fn.animationComplete.default = 1000; })( jQuery ); // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [], mouseEventProps = $.event.props.concat( mouseHookProps ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = "addEventListener" in document, $document = $( document ), nextTouchID = 1, lastTouchID = 0, threshold, i; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j, len; event = $.Event( event ); event.type = eventType; oe = event.originalEvent; props = $.event.props; // addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280 // https://github.com/jquery/jquery-mobile/issues/3280 if ( t.search( /^(mouse|click)/ ) > -1 ) { props = mouseEventProps; } // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } // make sure that if the mouse and click virtual events are generated // without a .which one is defined if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) { event.which = 1; } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++) { prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout( function() { resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ) { clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); } return ve; } function mouseEventCallback( event ) { var touchID = $.data( event.target, touchTargetPropertyName ), ve; if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) { ve = triggerVirtualEvent( "v" + event.type, event ); if ( ve ) { if ( ve.isDefaultPrevented() ) { event.preventDefault(); } if ( ve.isPropagationStopped() ) { event.stopPropagation(); } if ( ve.isImmediatePropagationStopped() ) { event.stopImmediatePropagation(); } } } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags, t; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold, flags = getVirtualBindingFlags( event.target ); didScroll = didScroll || ( Math.abs( t.pageX - startX ) > moveThreshold || Math.abs( t.pageY - startY ) > moveThreshold ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), ve, t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { ve = triggerVirtualEvent( "vclick", event, flags ); if ( ve && ve.isDefaultPrevented() ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler() {} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function(/* data, namespace */) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {} ); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if ( activeDocHandlers[ "touchstart" ] === 1 ) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function(/* data, namespace */) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( i = 0; i < virtualEventNames.length; i++ ) { $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ) { var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is synthesized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); (function( $, window, undefined ) { var $document = $( document ), supportTouch = $.mobile.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; // setup new event shortcuts $.each( ( "touchstart touchmove touchend " + "tap taphold " + "swipe swipeleft swiperight " + "scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ name ] = true; } }); function triggerCustomEvent( obj, eventType, event, bubble ) { var originalType = event.type; event.type = eventType; if ( bubble ) { $.event.trigger( event, undefined, obj ); } else { $.event.dispatch.call( obj, event ); } event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout( function() { trigger( event, false ); }, 50 ); }); }, teardown: function() { $( this ).unbind( scrollEvent ); } }; // also handles taphold $.event.special.tap = { tapholdThreshold: 750, emitTapOnTaphold: true, setup: function() { var thisObject = this, $this = $( thisObject ), isTaphold = false; $this.bind( "vmousedown", function( event ) { isTaphold = false; if ( event.which && event.which !== 1 ) { return false; } var origTarget = event.target, timer; function clearTapTimer() { clearTimeout( timer ); } function clearTapHandlers() { clearTapTimer(); $this.unbind( "vclick", clickHandler ) .unbind( "vmouseup", clearTapTimer ); $document.unbind( "vmousecancel", clearTapHandlers ); } function clickHandler( event ) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( !isTaphold && origTarget === event.target ) { triggerCustomEvent( thisObject, "tap", event ); } else if ( isTaphold ) { event.stopPropagation(); } } $this.bind( "vmouseup", clearTapTimer ) .bind( "vclick", clickHandler ); $document.bind( "vmousecancel", clearTapHandlers ); timer = setTimeout( function() { if ( !$.event.special.tap.emitTapOnTaphold ) { isTaphold = true; } triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) ); }, $.event.special.tap.tapholdThreshold ); }); }, teardown: function() { $( this ).unbind( "vmousedown" ).unbind( "vclick" ).unbind( "vmouseup" ); $document.unbind( "vmousecancel" ); } }; // Also handles swipeleft, swiperight $.event.special.swipe = { // More than this horizontal displacement, and we will suppress scrolling. scrollSupressionThreshold: 30, // More time than this, and it isn't a swipe. durationThreshold: 1000, // Swipe horizontal displacement must be more than this. horizontalDistanceThreshold: 30, // Swipe vertical displacement must be less than this. verticalDistanceThreshold: 30, getLocation: function ( event ) { var winPageX = window.pageXOffset, winPageY = window.pageYOffset, x = event.clientX, y = event.clientY; if ( event.pageY === 0 && Math.floor( y ) > Math.floor( event.pageY ) || event.pageX === 0 && Math.floor( x ) > Math.floor( event.pageX ) ) { // iOS4 clientX/clientY have the value that should have been // in pageX/pageY. While pageX/page/ have the value 0 x = x - winPageX; y = y - winPageY; } else if ( y < ( event.pageY - winPageY) || x < ( event.pageX - winPageX ) ) { // Some Android browsers have totally bogus values for clientX/Y // when scrolling/zooming a page. Detectable since clientX/clientY // should never be smaller than pageX/pageY minus page scroll x = event.pageX - winPageX; y = event.pageY - winPageY; } return { x: x, y: y }; }, start: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, location = $.event.special.swipe.getLocation( data ); return { time: ( new Date() ).getTime(), coords: [ location.x, location.y ], origin: $( event.target ) }; }, stop: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, location = $.event.special.swipe.getLocation( data ); return { time: ( new Date() ).getTime(), coords: [ location.x, location.y ] }; }, handleSwipe: function( start, stop, thisObject, origTarget ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { var direction = start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight"; triggerCustomEvent( thisObject, "swipe", $.Event( "swipe", { target: origTarget, swipestart: start, swipestop: stop }), true ); triggerCustomEvent( thisObject, direction,$.Event( direction, { target: origTarget, swipestart: start, swipestop: stop } ), true ); return true; } return false; }, // This serves as a flag to ensure that at most one swipe event event is // in work at any given time eventInProgress: false, setup: function() { var events, thisObject = this, $this = $( thisObject ), context = {}; // Retrieve the events data for this element and add the swipe context events = $.data( this, "mobile-events" ); if ( !events ) { events = { length: 0 }; $.data( this, "mobile-events", events ); } events.length++; events.swipe = context; context.start = function( event ) { // Bail if we're already working on a swipe event if ( $.event.special.swipe.eventInProgress ) { return; } $.event.special.swipe.eventInProgress = true; var stop, start = $.event.special.swipe.start( event ), origTarget = event.target, emitted = false; context.move = function( event ) { if ( !start ) { return; } stop = $.event.special.swipe.stop( event ); if ( !emitted ) { emitted = $.event.special.swipe.handleSwipe( start, stop, thisObject, origTarget ); if ( emitted ) { // Reset the context to make way for the next swipe event $.event.special.swipe.eventInProgress = false; } } // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } }; context.stop = function() { emitted = true; // Reset the context to make way for the next swipe event $.event.special.swipe.eventInProgress = false; $document.off( touchMoveEvent, context.move ); context.move = null; }; $document.on( touchMoveEvent, context.move ) .one( touchStopEvent, context.stop ); }; $this.on( touchStartEvent, context.start ); }, teardown: function() { var events, context; events = $.data( this, "mobile-events" ); if ( events ) { context = events.swipe; delete events.swipe; events.length--; if ( events.length === 0 ) { $.removeData( this, "mobile-events" ); } } if ( context ) { if ( context.start ) { $( this ).off( touchStartEvent, context.start ); } if ( context.move ) { $document.off( touchMoveEvent, context.move ); } if ( context.stop ) { $document.off( touchStopEvent, context.stop ); } } } }; $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); }, teardown: function() { $( this ).unbind( sourceEvent ); } }; }); })( jQuery, this ); // throttled resize event (function( $ ) { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function() { $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })( jQuery ); (function( $, window ) { var win = $( window ), event_name = "orientationchange", get_orientation, last_orientation, initial_orientation_is_landscape, initial_orientation_is_default, portrait_map = { "0": true, "180": true }, ww, wh, landscape_threshold; // It seems that some device/browser vendors use window.orientation values 0 and 180 to // denote the "default" orientation. For iOS devices, and most other smart-phones tested, // the default orientation is always "portrait", but in some Android and RIM based tablets, // the default orientation is "landscape". The following code attempts to use the window // dimensions to figure out what the current orientation is, and then makes adjustments // to the to the portrait_map if necessary, so that we can properly decode the // window.orientation value whenever get_orientation() is called. // // Note that we used to use a media query to figure out what the orientation the browser // thinks it is in: // // initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)"); // // but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1, // where the browser *ALWAYS* applied the landscape media query. This bug does not // happen on iPad. if ( $.support.orientation ) { // Check the window width and height to figure out what the current orientation // of the device is at this moment. Note that we've initialized the portrait map // values to 0 and 180, *AND* we purposely check for landscape so that if we guess // wrong, , we default to the assumption that portrait is the default orientation. // We use a threshold check below because on some platforms like iOS, the iPhone // form-factor can report a larger width than height if the user turns on the // developer console. The actual threshold value is somewhat arbitrary, we just // need to make sure it is large enough to exclude the developer console case. ww = window.innerWidth || win.width(); wh = window.innerHeight || win.height(); landscape_threshold = 50; initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold; // Now check to see if the current window.orientation is 0 or 180. initial_orientation_is_default = portrait_map[ window.orientation ]; // If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR* // if the initial orientation is portrait, but window.orientation reports 90 or -90, we // need to flip our portrait_map values because landscape is the default orientation for // this device/browser. if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) { portrait_map = { "-90": true, "90": true }; } } $.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function() { // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }); // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( event_name ); } } // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var isPortrait = true, elem = document.documentElement; // prefer window orientation to the calculation based on screensize as // the actual screen resize takes place before or after the orientation change event // has been fired depending on implementation (eg android 2.3 is before, iphone after). // More testing is required to determine if a more reliable method of determining the new screensize // is possible when orientationchange is fired. (eg, use media queries + element + opacity) if ( $.support.orientation ) { // if the window orientation registers as 0 or 180 degrees report // portrait, otherwise landscape isPortrait = portrait_map[ window.orientation ]; } else { isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1; } return isPortrait ? "portrait" : "landscape"; }; $.fn[ event_name ] = function( fn ) { return fn ? this.bind( event_name, fn ) : this.trigger( event_name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ event_name ] = true; } }( jQuery, this )); (function( $, undefined ) { // existing base tag? var baseElement = $( "head" ).children( "base" ), // base element management, defined depending on dynamic base tag support // TODO move to external widget base = { // define base element, for use in routing asset urls that are referenced // in Ajax-requested markup element: ( baseElement.length ? baseElement : $( "<base>", { href: $.mobile.path.documentBase.hrefNoHash } ).prependTo( $( "head" ) ) ), linkSelector: "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]", // set the generated BASE element's href to a new page's base path set: function( href ) { // we should do nothing if the user wants to manage their url base // manually if ( !$.mobile.dynamicBaseEnabled ) { return; } // we should use the base tag if we can manipulate it dynamically if ( $.support.dynamicBaseTag ) { base.element.attr( "href", $.mobile.path.makeUrlAbsolute( href, $.mobile.path.documentBase ) ); } }, rewrite: function( href, page ) { var newPath = $.mobile.path.get( href ); page.find( base.linkSelector ).each(function( i, link ) { var thisAttr = $( link ).is( "[href]" ) ? "href" : $( link ).is( "[src]" ) ? "src" : "action", thisUrl = $( link ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. // if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + "//" + location.host + location.pathname, "" ); if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( link ).attr( thisAttr, newPath + thisUrl ); } }); }, // set the generated BASE element's href to a new page's base path reset: function(/* href */) { base.element.attr( "href", $.mobile.path.documentBase.hrefNoSearch ); } }; $.mobile.base = base; })( jQuery ); (function( $, undefined ) { $.mobile.widgets = {}; var originalWidget = $.widget, // Record the original, non-mobileinit-modified version of $.mobile.keepNative // so we can later determine whether someone has modified $.mobile.keepNative keepNativeFactoryDefault = $.mobile.keepNative; $.widget = (function( orig ) { return function() { var constructor = orig.apply( this, arguments ), name = constructor.prototype.widgetName; constructor.initSelector = ( ( constructor.prototype.initSelector !== undefined ) ? constructor.prototype.initSelector : ":jqmData(role='" + name + "')" ); $.mobile.widgets[ name ] = constructor; return constructor; }; })( $.widget ); // Make sure $.widget still has bridge and extend methods $.extend( $.widget, originalWidget ); // For backcompat remove in 1.5 $.mobile.document.on( "create", function( event ) { $( event.target ).enhanceWithin(); }); $.widget( "mobile.page", { options: { theme: "a", domCache: false, // Deprecated in 1.4 remove in 1.5 keepNativeDefault: $.mobile.keepNative, // Deprecated in 1.4 remove in 1.5 contentTheme: null, enhanced: false }, // DEPRECATED for > 1.4 // TODO remove at 1.5 _createWidget: function() { $.Widget.prototype._createWidget.apply( this, arguments ); this._trigger( "init" ); }, _create: function() { // If false is returned by the callbacks do not create the page if ( this._trigger( "beforecreate" ) === false ) { return false; } if ( !this.options.enhanced ) { this._enhance(); } this._on( this.element, { pagebeforehide: "removeContainerBackground", pagebeforeshow: "_handlePageBeforeShow" }); this.element.enhanceWithin(); // Dialog widget is deprecated in 1.4 remove this in 1.5 if ( $.mobile.getAttribute( this.element[0], "role" ) === "dialog" && $.mobile.dialog ) { this.element.dialog(); } }, _enhance: function () { var attrPrefix = "data-" + $.mobile.ns, self = this; if ( this.options.role ) { this.element.attr( "data-" + $.mobile.ns + "role", this.options.role ); } this.element .attr( "tabindex", "0" ) .addClass( "ui-page ui-page-theme-" + this.options.theme ); // Manipulation of content os Deprecated as of 1.4 remove in 1.5 this.element.find( "[" + attrPrefix + "role='content']" ).each( function() { var $this = $( this ), theme = this.getAttribute( attrPrefix + "theme" ) || undefined; self.options.contentTheme = theme || self.options.contentTheme || ( self.options.dialog && self.options.theme ) || ( self.element.jqmData("role") === "dialog" && self.options.theme ); $this.addClass( "ui-content" ); if ( self.options.contentTheme ) { $this.addClass( "ui-body-" + ( self.options.contentTheme ) ); } // Add ARIA role $this.attr( "role", "main" ).addClass( "ui-content" ); }); }, bindRemove: function( callback ) { var page = this.element; // when dom caching is not enabled or the page is embedded bind to remove the page on hide if ( !page.data( "mobile-page" ).options.domCache && page.is( ":jqmData(external-page='true')" ) ) { // TODO use _on - that is, sort out why it doesn't work in this case page.bind( "pagehide.remove", callback || function( e, data ) { //check if this is a same page transition and if so don't remove the page if( !data.samePage ){ var $this = $( this ), prEvent = new $.Event( "pageremove" ); $this.trigger( prEvent ); if ( !prEvent.isDefaultPrevented() ) { $this.removeWithDependents(); } } }); } }, _setOptions: function( o ) { if ( o.theme !== undefined ) { this.element.removeClass( "ui-page-theme-" + this.options.theme ).addClass( "ui-page-theme-" + o.theme ); } if ( o.contentTheme !== undefined ) { this.element.find( "[data-" + $.mobile.ns + "='content']" ).removeClass( "ui-body-" + this.options.contentTheme ) .addClass( "ui-body-" + o.contentTheme ); } }, _handlePageBeforeShow: function(/* e */) { this.setContainerBackground(); }, // Deprecated in 1.4 remove in 1.5 removeContainerBackground: function() { this.element.closest( ":mobile-pagecontainer" ).pagecontainer({ "theme": "none" }); }, // Deprecated in 1.4 remove in 1.5 // set the page container background to the page theme setContainerBackground: function( theme ) { this.element.parent().pagecontainer( { "theme": theme || this.options.theme } ); }, // Deprecated in 1.4 remove in 1.5 keepNativeSelector: function() { var options = this.options, keepNative = $.trim( options.keepNative || "" ), globalValue = $.trim( $.mobile.keepNative ), optionValue = $.trim( options.keepNativeDefault ), // Check if $.mobile.keepNative has changed from the factory default newDefault = ( keepNativeFactoryDefault === globalValue ? "" : globalValue ), // If $.mobile.keepNative has not changed, use options.keepNativeDefault oldDefault = ( newDefault === "" ? optionValue : "" ); // Concatenate keepNative selectors from all sources where the value has // changed or, if nothing has changed, return the default return ( ( keepNative ? [ keepNative ] : [] ) .concat( newDefault ? [ newDefault ] : [] ) .concat( oldDefault ? [ oldDefault ] : [] ) .join( ", " ) ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.pagecontainer", { options: { theme: "a" }, initSelector: false, _create: function() { this.setLastScrollEnabled = true; // TODO consider moving the navigation handler OUT of widget into // some other object as glue between the navigate event and the // content widget load and change methods this._on( this.window, { navigate: "_filterNavigateEvents" }); this._on( this.window, { // disable an scroll setting when a hashchange has been fired, // this only works because the recording of the scroll position // is delayed for 100ms after the browser might have changed the // position because of the hashchange navigate: "_disableRecordScroll", // bind to scrollstop for the first page, "pagechange" won't be // fired in that case scrollstop: "_delayedRecordScroll" }); // TODO move from page* events to content* events this._on({ pagechange: "_afterContentChange" }); // handle initial hashchange from chrome :( this.window.one( "navigate", $.proxy(function() { this.setLastScrollEnabled = true; }, this)); }, _setOptions: function( options ) { if ( options.theme !== undefined && options.theme !== "none" ) { this.element.removeClass( "ui-overlay-" + this.options.theme ) .addClass( "ui-overlay-" + options.theme ); } else if ( options.theme !== undefined ) { this.element.removeClass( "ui-overlay-" + this.options.theme ); } this._super( options ); }, _disableRecordScroll: function() { this.setLastScrollEnabled = false; }, _enableRecordScroll: function() { this.setLastScrollEnabled = true; }, // TODO consider the name here, since it's purpose specific _afterContentChange: function() { // once the page has changed, re-enable the scroll recording this.setLastScrollEnabled = true; // remove any binding that previously existed on the get scroll // which may or may not be different than the scroll element // determined for this page previously this._off( this.window, "scrollstop" ); // determine and bind to the current scoll element which may be the // window or in the case of touch overflow the element touch overflow this._on( this.window, { scrollstop: "_delayedRecordScroll" }); }, _recordScroll: function() { // this barrier prevents setting the scroll value based on // the browser scrolling the window based on a hashchange if ( !this.setLastScrollEnabled ) { return; } var active = this._getActiveHistory(), currentScroll, minScroll, defaultScroll; if ( active ) { currentScroll = this._getScroll(); minScroll = this._getMinScroll(); defaultScroll = this._getDefaultScroll(); // Set active page's lastScroll prop. If the location we're // scrolling to is less than minScrollBack, let it go. active.lastScroll = currentScroll < minScroll ? defaultScroll : currentScroll; } }, _delayedRecordScroll: function() { setTimeout( $.proxy(this, "_recordScroll"), 100 ); }, _getScroll: function() { return this.window.scrollTop(); }, _getMinScroll: function() { return $.mobile.minScrollBack; }, _getDefaultScroll: function() { return $.mobile.defaultHomeScroll; }, _filterNavigateEvents: function( e, data ) { var url; if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) { return; } url = e.originalEvent.type.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url; if ( !url ) { url = this._getHash(); } if ( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ) { url = location.href; } this._handleNavigate( url, data.state ); }, _getHash: function() { return $.mobile.path.parseLocation().hash; }, // TODO active page should be managed by the container (ie, it should be a property) getActivePage: function() { return this.activePage; }, // TODO the first page should be a property set during _create using the logic // that currently resides in init _getInitialContent: function() { return $.mobile.firstPage; }, // TODO each content container should have a history object _getHistory: function() { return $.mobile.navigate.history; }, // TODO use _getHistory _getActiveHistory: function() { return $.mobile.navigate.history.getActive(); }, // TODO the document base should be determined at creation _getDocumentBase: function() { return $.mobile.path.documentBase; }, back: function() { this.go( -1 ); }, forward: function() { this.go( 1 ); }, go: function( steps ) { //if hashlistening is enabled use native history method if ( $.mobile.hashListeningEnabled ) { window.history.go( steps ); } else { //we are not listening to the hash so handle history internally var activeIndex = $.mobile.navigate.history.activeIndex, index = activeIndex + parseInt( steps, 10 ), url = $.mobile.navigate.history.stack[ index ].url, direction = ( steps >= 1 )? "forward" : "back"; //update the history object $.mobile.navigate.history.activeIndex = index; $.mobile.navigate.history.previousIndex = activeIndex; //change to the new page this.change( url, { direction: direction, changeHash: false, fromHashChange: true } ); } }, // TODO rename _handleDestination _handleDestination: function( to ) { var history; // clean the hash for comparison if it's a url if ( $.type(to) === "string" ) { to = $.mobile.path.stripHash( to ); } if ( to ) { history = this._getHistory(); // At this point, 'to' can be one of 3 things, a cached page // element from a history stack entry, an id, or site-relative / // absolute URL. If 'to' is an id, we need to resolve it against // the documentBase, not the location.href, since the hashchange // could've been the result of a forward/backward navigation // that crosses from an external page/dialog to an internal // page/dialog. // // TODO move check to history object or path object? to = !$.mobile.path.isPath( to ) ? ( $.mobile.path.makeUrlAbsolute( "#" + to, this._getDocumentBase() ) ) : to; // If we're about to go to an initial URL that contains a // reference to a non-existent internal page, go to the first // page instead. We know that the initial hash refers to a // non-existent page, because the initial hash did not end // up in the initial history entry // TODO move check to history object? if ( to === $.mobile.path.makeUrlAbsolute( "#" + history.initialDst, this._getDocumentBase() ) && history.stack.length && history.stack[0].url !== history.initialDst.replace( $.mobile.dialogHashKey, "" ) ) { to = this._getInitialContent(); } } return to || this._getInitialContent(); }, _handleDialog: function( changePageOptions, data ) { var to, active, activeContent = this.getActivePage(); // If current active page is not a dialog skip the dialog and continue // in the same direction if ( activeContent && !activeContent.hasClass( "ui-dialog" ) ) { // determine if we're heading forward or backward and continue // accordingly past the current dialog if ( data.direction === "back" ) { this.back(); } else { this.forward(); } // prevent changePage call return false; } else { // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack to = data.pageUrl; active = this._getActiveHistory(); // make sure to set the role, transition and reversal // as most of this is lost by the domCache cleaning $.extend( changePageOptions, { role: active.role, transition: active.transition, reverse: data.direction === "back" }); } return to; }, _handleNavigate: function( url, data ) { //find first page via hash // TODO stripping the hash twice with handleUrl var to = $.mobile.path.stripHash( url ), history = this._getHistory(), // transition is false if it's the first page, undefined // otherwise (and may be overridden by default) transition = history.stack.length === 0 ? "none" : undefined, // default options for the changPage calls made after examining // the current state of the page and the hash, NOTE that the // transition is derived from the previous history entry changePageOptions = { changeHash: false, fromHashChange: true, reverse: data.direction === "back" }; $.extend( changePageOptions, data, { transition: ( history.getLast() || {} ).transition || transition }); // TODO move to _handleDestination ? // If this isn't the first page, if the current url is a dialog hash // key, and the initial destination isn't equal to the current target // page, use the special dialog handling if ( history.activeIndex > 0 && to.indexOf( $.mobile.dialogHashKey ) > -1 && history.initialDst !== to ) { to = this._handleDialog( changePageOptions, data ); if ( to === false ) { return; } } this._changeContent( this._handleDestination( to ), changePageOptions ); }, _changeContent: function( to, opts ) { $.mobile.changePage( to, opts ); }, _getBase: function() { return $.mobile.base; }, _getNs: function() { return $.mobile.ns; }, _enhance: function( content, role ) { // TODO consider supporting a custom callback, and passing in // the settings which includes the role return content.page({ role: role }); }, _include: function( page, settings ) { // append to page and enhance page.appendTo( this.element ); // use the page widget to enhance this._enhance( page, settings.role ); // remove page on hide page.page( "bindRemove" ); }, _find: function( absUrl ) { // TODO consider supporting a custom callback var fileUrl = this._createFileUrl( absUrl ), dataUrl = this._createDataUrl( absUrl ), page, initialContent = this._getInitialContent(); // Check to see if the page already exists in the DOM. // NOTE do _not_ use the :jqmData pseudo selector because parenthesis // are a valid url char and it breaks on the first occurence page = this.element .children( "[data-" + this._getNs() +"url='" + dataUrl + "']" ); // If we failed to find the page, check to see if the url is a // reference to an embedded page. If so, it may have been dynamically // injected by a developer, in which case it would be lacking a // data-url attribute and in need of enhancement. if ( page.length === 0 && dataUrl && !$.mobile.path.isPath( dataUrl ) ) { page = this.element.children( $.mobile.path.hashToSelector("#" + dataUrl) ) .attr( "data-" + this._getNs() + "url", dataUrl ) .jqmData( "url", dataUrl ); } // If we failed to find a page in the DOM, check the URL to see if it // refers to the first page in the application. Also check to make sure // our cached-first-page is actually in the DOM. Some user deployed // apps are pruning the first page from the DOM for various reasons. // We check for this case here because we don't want a first-page with // an id falling through to the non-existent embedded page error case. if ( page.length === 0 && $.mobile.path.isFirstPageUrl( fileUrl ) && initialContent && initialContent.parent().length ) { page = $( initialContent ); } return page; }, _getLoader: function() { return $.mobile.loading(); }, _showLoading: function( delay, theme, msg, textonly ) { // This configurable timeout allows cached pages a brief // delay to load without showing a message if ( this._loadMsg ) { return; } this._loadMsg = setTimeout($.proxy(function() { this._getLoader().loader( "show", theme, msg, textonly ); this._loadMsg = 0; }, this), delay ); }, _hideLoading: function() { // Stop message show timer clearTimeout( this._loadMsg ); this._loadMsg = 0; // Hide loading message this._getLoader().loader( "hide" ); }, _showError: function() { // make sure to remove the current loading message this._hideLoading(); // show the error message this._showLoading( 0, $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true ); // hide the error message after a delay // TODO configuration setTimeout( $.proxy(this, "_hideLoading"), 1500 ); }, _parse: function( html, fileUrl ) { // TODO consider allowing customization of this method. It's very JQM specific var page, all = $( "<div></div>" ); //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if ( !page.length ) { page = $( "<div data-" + this._getNs() + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" ); } // TODO tagging a page with external to make sure that embedded pages aren't // removed by the various page handling code is bad. Having page handling code // in many places is bad. Solutions post 1.0 page.attr( "data-" + this._getNs() + "url", $.mobile.path.convertUrlToDataUrl(fileUrl) ) .attr( "data-" + this._getNs() + "external-page", true ); return page; }, _setLoadedTitle: function( page, html ) { //page title regexp var newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1; if ( newPageTitle && !page.jqmData("title") ) { newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text(); page.jqmData( "title", newPageTitle ); } }, _isRewritableBaseTag: function() { return $.mobile.dynamicBaseEnabled && !$.support.dynamicBaseTag; }, _createDataUrl: function( absoluteUrl ) { return $.mobile.path.convertUrlToDataUrl( absoluteUrl ); }, _createFileUrl: function( absoluteUrl ) { return $.mobile.path.getFilePath( absoluteUrl ); }, _triggerWithDeprecated: function( name, data, page ) { var deprecatedEvent = $.Event( "page" + name ), newEvent = $.Event( this.widgetName + name ); // DEPRECATED // trigger the old deprecated event on the page if it's provided ( page || this.element ).trigger( deprecatedEvent, data ); // use the widget trigger method for the new content* event this.element.trigger( newEvent, data ); return { deprecatedEvent: deprecatedEvent, event: newEvent }; }, // TODO it would be nice to split this up more but everything appears to be "one off" // or require ordering such that other bits are sprinkled in between parts that // could be abstracted out as a group _loadSuccess: function( absUrl, triggerData, settings, deferred ) { var fileUrl = this._createFileUrl( absUrl ), dataUrl = this._createDataUrl( absUrl ); return $.proxy(function( html, textStatus, xhr ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var content, // TODO handle dialogs again pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + this._getNs() + "role=[\"']?page[\"']?[^>]*>)" ), dataUrlRegex = new RegExp( "\\bdata-" + this._getNs() + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests // can be directed to the correct url. loading into a temprorary // element makes these requests immediately if ( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { fileUrl = $.mobile.path.getFilePath( $("<div>" + RegExp.$1 + "</div>").text() ); } //dont update the base tag if we are prefetching if ( settings.prefetch === undefined ) { this._getBase().set( fileUrl ); } content = this._parse( html, fileUrl ); this._setLoadedTitle( content, html ); // Add the content reference and xhr to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; // DEPRECATED triggerData.page = content; triggerData.content = content; // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if ( !this._trigger( "load", undefined, triggerData ) ) { return; } // rewrite src and href attrs to use a base url if the base tag won't work if ( this._isRewritableBaseTag() && content ) { this._getBase().rewrite( fileUrl, content ); } this._include( content, settings ); // Enhancing the content may result in new dialogs/sub content being inserted // into the DOM. If the original absUrl refers to a sub-content, that is the // real content we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { content = this.element.children( "[data-" + this._getNs() +"url='" + dataUrl + "']" ); } // Remove loading message. if ( settings.showLoadMsg ) { this._hideLoading(); } // BEGIN DEPRECATED --------------------------------------------------- // Let listeners know the content loaded successfully. this.element.trigger( "pageload" ); // END DEPRECATED ----------------------------------------------------- deferred.resolve( absUrl, settings, content ); }, this); }, _loadDefaults: { type: "get", data: undefined, // DEPRECATED reloadPage: false, reload: false, // By default we rely on the role defined by the @data-role attribute. role: undefined, showLoadMsg: false, // This delay allows loads that pull from browser cache to // occur without showing the loading message. loadMsgDelay: 50 }, load: function( url, options ) { // This function uses deferred notifications to let callers // know when the content is done loading, or if an error has occurred. var deferred = ( options && options.deferred ) || $.Deferred(), // The default load options with overrides specified by the caller. settings = $.extend( {}, this._loadDefaults, options ), // The DOM element for the content after it has been loaded. content = null, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subcontent params in it. absUrl = $.mobile.path.makeUrlAbsolute( url, this._findBaseWithDefault() ), fileUrl, dataUrl, pblEvent, triggerData; // DEPRECATED reloadPage settings.reload = settings.reloadPage; // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = $.mobile.path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // If the caller is using a "post" request, reload must be true if ( settings.data && settings.type === "post" ) { settings.reload = true; } // The absolute version of the URL minus any dialog/subcontent params. // In otherwords the real URL of the content to be loaded. fileUrl = this._createFileUrl( absUrl ); // The version of the Url actually stored in the data-url attribute of // the content. For embedded content, it is just the id of the page. For // content within the same domain as the document base, it is the site // relative path. For cross-domain content (Phone Gap only) the entire // absolute Url is used to load the content. dataUrl = this._createDataUrl( absUrl ); content = this._find( absUrl ); // If it isn't a reference to the first content and refers to missing // embedded content reject the deferred and return if ( content.length === 0 && $.mobile.path.isEmbeddedPage(fileUrl) && !$.mobile.path.isFirstPageUrl(fileUrl) ) { deferred.reject( absUrl, settings ); return; } // Reset base to the default document base // TODO figure out why we doe this this._getBase().reset(); // If the content we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Resolve the deferrred so that // users can bind to .done on the promise if ( content.length && !settings.reload ) { this._enhance( content, settings.role ); deferred.resolve( absUrl, settings, content ); //if we are reloading the content make sure we update // the base if its not a prefetch if ( !settings.prefetch ) { this._getBase().set(url); } return; } triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings }; // Let listeners know we're about to load content. pblEvent = this._triggerWithDeprecated( "beforeload", triggerData ); // If the default behavior is prevented, stop here! if ( pblEvent.deprecatedEvent.isDefaultPrevented() || pblEvent.event.isDefaultPrevented() ) { return; } if ( settings.showLoadMsg ) { this._showLoading( settings.loadMsgDelay ); } // Reset base to the default document base. // only reset if we are not prefetching if ( settings.prefetch === undefined ) { this._getBase().reset(); } if ( !( $.mobile.allowCrossDomainPages || $.mobile.path.isSameDomain($.mobile.path.documentUrl, absUrl ) ) ) { deferred.reject( absUrl, settings ); return; } // Load the new content. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, contentType: settings.contentType, dataType: "html", success: this._loadSuccess( absUrl, triggerData, settings, deferred ), error: this._loadError( absUrl, triggerData, settings, deferred ) }); }, _loadError: function( absUrl, triggerData, settings, deferred ) { return $.proxy(function( xhr, textStatus, errorThrown ) { //set base back to current path this._getBase().set( $.mobile.path.get() ); // Add error info to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; triggerData.errorThrown = errorThrown; // Let listeners know the page load failed. var plfEvent = this._triggerWithDeprecated( "loadfailed", triggerData ); // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if ( plfEvent.deprecatedEvent.isDefaultPrevented() || plfEvent.event.isDefaultPrevented() ) { return; } // Remove loading message. if ( settings.showLoadMsg ) { this._showError(); } deferred.reject( absUrl, settings ); }, this); }, _getTransitionHandler: function( transition ) { transition = $.mobile._maybeDegradeTransition( transition ); //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. return $.mobile.transitionHandlers[ transition ] || $.mobile.defaultTransitionHandler; }, // TODO move into transition handlers? _triggerCssTransitionEvents: function( to, from, prefix ) { var samePage = false; prefix = prefix || ""; // TODO decide if these events should in fact be triggered on the container if ( from ) { //Check if this is a same page transition and tell the handler in page if( to[0] === from[0] ){ samePage = true; } //trigger before show/hide events // TODO deprecate nextPage in favor of next this._triggerWithDeprecated( prefix + "hide", { nextPage: to, samePage: samePage }, from ); } // TODO deprecate prevPage in favor of previous this._triggerWithDeprecated( prefix + "show", { prevPage: from || $( "" ) }, to ); }, // TODO make private once change has been defined in the widget _cssTransition: function( to, from, options ) { var transition = options.transition, reverse = options.reverse, deferred = options.deferred, TransitionHandler, promise; this._triggerCssTransitionEvents( to, from, "before" ); // TODO put this in a binding to events *outside* the widget this._hideLoading(); TransitionHandler = this._getTransitionHandler( transition ); promise = ( new TransitionHandler( transition, reverse, to, from ) ).transition(); // TODO temporary accomodation of argument deferred promise.done(function() { deferred.resolve.apply( deferred, arguments ); }); promise.done($.proxy(function() { this._triggerCssTransitionEvents( to, from ); }, this)); }, _releaseTransitionLock: function() { //release transition lock so navigation is free again isPageTransitioning = false; if ( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } }, _removeActiveLinkClass: function( force ) { //clear out the active button state $.mobile.removeActiveLinkClass( force ); }, _loadUrl: function( to, triggerData, settings ) { // preserve the original target as the dataUrl value will be // simplified eg, removing ui-state, and removing query params // from the hash this is so that users who want to use query // params have access to them in the event bindings for the page // life cycle See issue #5085 settings.target = to; settings.deferred = $.Deferred(); this.load( to, settings ); settings.deferred.done($.proxy(function( url, options, content ) { isPageTransitioning = false; // store the original absolute url so that it can be provided // to events in the triggerData of the subsequent changePage call options.absUrl = triggerData.absUrl; this.transition( content, triggerData, options ); }, this)); settings.deferred.fail($.proxy(function(/* url, options */) { this._removeActiveLinkClass( true ); this._releaseTransitionLock(); this._triggerWithDeprecated( "changefailed", triggerData ); }, this)); }, _triggerPageBeforeChange: function( to, triggerData, settings ) { var pbcEvent = new $.Event( "pagebeforechange" ); $.extend(triggerData, { toPage: to, options: settings }); // NOTE: preserve the original target as the dataUrl value will be // simplified eg, removing ui-state, and removing query params from // the hash this is so that users who want to use query params have // access to them in the event bindings for the page life cycle // See issue #5085 if ( $.type(to) === "string" ) { // if the toPage is a string simply convert it triggerData.absUrl = $.mobile.path.makeUrlAbsolute( to, this._findBaseWithDefault() ); } else { // if the toPage is a jQuery object grab the absolute url stored // in the loadPage callback where it exists triggerData.absUrl = settings.absUrl; } // Let listeners know we're about to change the current page. this.element.trigger( pbcEvent, triggerData ); // If the default behavior is prevented, stop here! if ( pbcEvent.isDefaultPrevented() ) { return false; } return true; }, change: function( to, options ) { // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition // to service the request. if ( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } var settings = $.extend( {}, $.mobile.changePage.defaults, options ), triggerData = {}; // Make sure we have a fromPage. settings.fromPage = settings.fromPage || this.activePage; // if the page beforechange default is prevented return early if ( !this._triggerPageBeforeChange(to, triggerData, settings) ) { return; } // We allow "pagebeforechange" observers to modify the to in // the trigger data to allow for redirects. Make sure our to is // updated. We also need to re-evaluate whether it is a string, // because an object can also be replaced by a string to = triggerData.toPage; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( $.type(to) === "string" ) { // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; this._loadUrl( to, triggerData, settings ); } else { this.transition( to, triggerData, settings ); } }, transition: function( toPage, triggerData, settings ) { var fromPage, url, pageUrl, fileUrl, active, activeIsInitialPage, historyDir, pageTitle, isDialog, alreadyThere, newPageTitle, params, cssTransitionDeferred, beforeTransition; // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition // to service the request. if ( isPageTransitioning ) { // make sure to only queue the to and settings values so the arguments // work with a call to the change method pageTransitionQueue.unshift( [toPage, settings] ); return; } // DEPRECATED - this call only, in favor of the before transition // if the page beforechange default is prevented return early if ( !this._triggerPageBeforeChange(toPage, triggerData, settings) ) { return; } // if the (content|page)beforetransition default is prevented return early // Note, we have to check for both the deprecated and new events beforeTransition = this._triggerWithDeprecated( "beforetransition", triggerData ); if (beforeTransition.deprecatedEvent.isDefaultPrevented() || beforeTransition.event.isDefaultPrevented() ) { return; } // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; // If we are going to the first-page of the application, we need to make // sure settings.dataUrl is set to the application document url. This allows // us to avoid generating a document url with an id hash in the case where the // first-page of the document has an id attribute specified. if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) { settings.dataUrl = $.mobile.path.documentUrl.hrefNoHash; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. fromPage = settings.fromPage; url = ( settings.dataUrl && $.mobile.path.convertUrlToDataUrl(settings.dataUrl) ) || toPage.jqmData( "url" ); // The pageUrl var is usually the same as url, except when url is obscured // as a dialog url. pageUrl always contains the file path pageUrl = url; fileUrl = $.mobile.path.getFilePath( url ); active = $.mobile.navigate.history.getActive(); activeIsInitialPage = $.mobile.navigate.history.activeIndex === 0; historyDir = 0; pageTitle = document.title; isDialog = ( settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog" ) && toPage.jqmData( "dialog" ) !== true; // By default, we prevent changePage requests when the fromPage and toPage // are the same element, but folks that generate content // manually/dynamically and reuse pages want to be able to transition to // the same page. To allow this, they will need to change the default // value of allowSamePageTransition to true, *OR*, pass it in as an // option when they manually call changePage(). It should be noted that // our default transition animations assume that the formPage and toPage // are different elements, so they may behave unexpectedly. It is up to // the developer that turns on the allowSamePageTransitiona option to // either turn off transition animations, or make sure that an appropriate // animation transition is used. if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) { isPageTransitioning = false; this._triggerWithDeprecated( "transition", triggerData ); this.element.trigger( "pagechange", triggerData ); // Even if there is no page change to be done, we should keep the // urlHistory in sync with the hash changes if ( settings.fromHashChange ) { $.mobile.navigate.history.direct({ url: url }); } return; } // We need to make sure the page we are given has already been enhanced. toPage.page({ role: settings.role }); // If the changePage request was sent from a hashChange event, check to // see if the page is already within the urlHistory stack. If so, we'll // assume the user hit the forward/back button and will try to match the // transition accordingly. if ( settings.fromHashChange ) { historyDir = settings.direction === "back" ? -1 : 1; } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. // Instead, we should be tracking focus with a delegate() // handler so we already have the element in hand at this // point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if // document.activeElement is undefined when we are in an IFrame. try { if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { $( document.activeElement ).blur(); } else { $( "input:focus, textarea:focus, select:focus" ).blur(); } } catch( e ) {} // Record whether we are at a place in history where a dialog used to be - // if so, do not add a new history entry and do not change the hash either alreadyThere = false; // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { // on the initial page load active.url is undefined and in that case // should be an empty string. Moving the undefined -> empty string back // into urlHistory.addNew seemed imprudent given undefined better // represents the url state // If we are at a place in history that once belonged to a dialog, reuse // this state without adding to urlHistory and without modifying the // hash. However, if a dialog is already displayed at this point, and // we're about to display another dialog, then we must add another hash // and history entry on top so that one may navigate back to the // original dialog if ( active.url && active.url.indexOf( $.mobile.dialogHashKey ) > -1 && this.activePage && !this.activePage.hasClass( "ui-dialog" ) && $.mobile.navigate.history.activeIndex > 0 ) { settings.changeHash = false; alreadyThere = true; } // Normally, we tack on a dialog hash key, but if this is the location // of a stale dialog, we reuse the URL from the entry url = ( active.url || "" ); // account for absolute urls instead of just relative urls use as hashes if ( !alreadyThere && url.indexOf("#") > -1 ) { url += $.mobile.dialogHashKey; } else { url += "#" + $.mobile.dialogHashKey; } // tack on another dialogHashKey if this is the same as the initial hash // this makes sure that a history entry is created for this dialog if ( $.mobile.navigate.history.activeIndex === 0 && url === $.mobile.navigate.history.initialDst ) { url += $.mobile.dialogHashKey; } } // if title element wasn't found, try the page div data attr too // If this is a deep-link or a reload ( active === undefined ) then just // use pageTitle newPageTitle = ( !active ) ? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text(); if ( !!newPageTitle && pageTitle === document.title ) { pageTitle = newPageTitle; } if ( !toPage.jqmData( "title" ) ) { toPage.jqmData( "title", pageTitle ); } // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); //add page to history stack if it's not back or forward if ( !historyDir && alreadyThere ) { $.mobile.navigate.history.getActive().pageUrl = pageUrl; } // Set the location hash. if ( url && !settings.fromHashChange ) { // rebuilding the hash here since we loose it earlier on // TODO preserve the originally passed in path if ( !$.mobile.path.isPath( url ) && url.indexOf( "#" ) < 0 ) { url = "#" + url; } // TODO the property names here are just silly params = { transition: settings.transition, title: pageTitle, pageUrl: pageUrl, role: settings.role }; if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) { $.mobile.navigate( url, params, true); } else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) { $.mobile.navigate.history.add( url, params ); } } //set page title document.title = pageTitle; //set "toPage" as activePage deprecated in 1.4 remove in 1.5 $.mobile.activePage = toPage; //new way to handle activePage this.activePage = toPage; // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; cssTransitionDeferred = $.Deferred(); this._cssTransition(toPage, fromPage, { transition: settings.transition, reverse: settings.reverse, deferred: cssTransitionDeferred }); cssTransitionDeferred.done($.proxy(function( name, reverse, $to, $from, alreadyFocused ) { $.mobile.removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } // despite visibility: hidden addresses issue #2965 // https://github.com/jquery/jquery-mobile/issues/2965 if ( !alreadyFocused ) { $.mobile.focusPage( toPage ); } this._releaseTransitionLock(); this.element.trigger( "pagechange", triggerData ); this._triggerWithDeprecated( "transition", triggerData ); }, this)); }, // determine the current base url _findBaseWithDefault: function() { var closestBase = ( this.activePage && $.mobile.getClosestBaseUrl( this.activePage ) ); return closestBase || $.mobile.path.documentBase.hrefNoHash; } }); // The following handlers should be bound after mobileinit has been triggered // the following deferred is resolved in the init file $.mobile.navreadyDeferred = $.Deferred(); //these variables make all page containers use the same queue and only navigate one at a time // queue to hold simultanious page transitions var pageTransitionQueue = [], // indicates whether or not page is in process of transitioning isPageTransitioning = false; })( jQuery ); (function( $, undefined ) { // resolved on domready var domreadyDeferred = $.Deferred(), documentUrl = $.mobile.path.documentUrl, // used to track last vclicked element to make sure its value is added to form data $lastVClicked = null; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { // Look for the closest element with a nodeName of "a". // Note that we are checking if we have a valid nodeName // before attempting to access it. This is because the // node we get called with could have originated from within // an embedded SVG document where some symbol instance elements // don't have nodeName defined on them, or strings are of type // SVGAnimatedString. if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) { break; } ele = ele.parentNode; } return ele; } $.mobile.loadPage = function( url, opts ) { var container; opts = opts || {}; container = ( opts.pageContainer || $.mobile.pageContainer ); // create the deferred that will be supplied to loadPage callers // and resolved by the content widget's load method opts.deferred = $.Deferred(); // Preferring to allow exceptions for uninitialized opts.pageContainer // widgets so we know if we need to force init here for users container.pagecontainer( "load", url, opts ); // provide the deferred return opts.deferred.promise(); }; //define vars for interal use /* internal utility functions */ // NOTE Issue #4950 Android phonegap doesn't navigate back properly // when a full page refresh has taken place. It appears that hashchange // and replacestate history alterations work fine but we need to support // both forms of history traversal in our code that uses backward history // movement $.mobile.back = function() { var nav = window.navigator; // if the setting is on and the navigator object is // available use the phonegap navigation capability if ( this.phonegapNavigationEnabled && nav && nav.app && nav.app.backHistory ) { nav.app.backHistory(); } else { $.mobile.pageContainer.pagecontainer( "back" ); } }; // Direct focus to the page title, or otherwise first focusable element $.mobile.focusPage = function ( page ) { var autofocus = page.find( "[autofocus]" ), pageTitle = page.find( ".ui-title:eq(0)" ); if ( autofocus.length ) { autofocus.focus(); return; } if ( pageTitle.length ) { pageTitle.focus(); } else{ page.focus(); } }; // No-op implementation of transition degradation $.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) { return transition; }; // Exposed $.mobile methods $.mobile.changePage = function( to, options ) { $.mobile.pageContainer.pagecontainer( "change", to, options ); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage dataUrl: undefined, fromPage: undefined, allowSamePageTransition: false }; $.mobile._registerInternalEvents = function() { var getAjaxFormData = function( $form, calculateOnly ) { var url, ret = true, formData, vclickedName, method; if ( !$.mobile.ajaxEnabled || // test that the form is, itself, ajax false $form.is( ":jqmData(ajax='false')" ) || // test that $.mobile.ignoreContentEnabled is set and // the form or one of it's parents is ajax=false !$form.jqmHijackable().length || $form.attr( "target" ) ) { return false; } url = ( $lastVClicked && $lastVClicked.attr( "formaction" ) ) || $form.attr( "action" ); method = ( $form.attr( "method" ) || "get" ).toLowerCase(); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = $.mobile.getClosestBaseUrl( $form ); // NOTE: If the method is "get", we need to strip off the query string // because it will get replaced with the new form data. See issue #5710. if ( method === "get" ) { url = $.mobile.path.parseUrl( url ).hrefNoSearch; } if ( url === $.mobile.path.documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = $.mobile.path.makeUrlAbsolute( url, $.mobile.getClosestBaseUrl( $form ) ); if ( ( $.mobile.path.isExternal( url ) && !$.mobile.path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) { return false; } if ( !calculateOnly ) { formData = $form.serializeArray(); if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) { vclickedName = $lastVClicked.attr( "name" ); if ( vclickedName ) { // Make sure the last clicked element is included in the form $.each( formData, function( key, value ) { if ( value.name === vclickedName ) { // Unset vclickedName - we've found it in the serialized data already vclickedName = ""; return false; } }); if ( vclickedName ) { formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } ); } } } ret = { url: url, options: { type: method, data: $.param( formData ), transition: $form.jqmData( "transition" ), reverse: $form.jqmData( "direction" ) === "reverse", reloadPage: true } }; } return ret; }; //bind to form submit events, handle with Ajax $.mobile.document.delegate( "form", "submit", function( event ) { var formData; if ( !event.isDefaultPrevented() ) { formData = getAjaxFormData( $( this ) ); if ( formData ) { $.mobile.changePage( formData.url, formData.options ); event.preventDefault(); } } }); //add active state on vclick $.mobile.document.bind( "vclick", function( event ) { var $btn, btnEls, target = event.target, needClosest = false; // if this isn't a left click we don't care. Its important to note // that when the virtual event is generated it will create the which attr if ( event.which > 1 || !$.mobile.linkBindingEnabled ) { return; } // Record that this element was clicked, in case we need it for correct // form submission during the "submit" handler above $lastVClicked = $( target ); // Try to find a target element to which the active class will be applied if ( $.data( target, "mobile-button" ) ) { // If the form will not be submitted via AJAX, do not add active class if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) { return; } // We will apply the active state to this button widget - the parent // of the input that was clicked will have the associated data if ( target.parentNode ) { target = target.parentNode; } } else { target = findClosestLink( target ); if ( !( target && $.mobile.path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) { return; } // TODO teach $.mobile.hijackable to operate on raw dom elements so the // link wrapping can be avoided if ( !$( target ).jqmHijackable().length ) { return; } } // Avoid calling .closest by using the data set during .buttonMarkup() // List items have the button data in the parent of the element clicked if ( !!~target.className.indexOf( "ui-link-inherit" ) ) { if ( target.parentNode ) { btnEls = $.data( target.parentNode, "buttonElements" ); } // Otherwise, look for the data on the target itself } else { btnEls = $.data( target, "buttonElements" ); } // If found, grab the button's outer element if ( btnEls ) { target = btnEls.outer; } else { needClosest = true; } $btn = $( target ); // If the outer element wasn't found by the our heuristics, use .closest() if ( needClosest ) { $btn = $btn.closest( ".ui-btn" ); } if ( $btn.length > 0 && !( $btn.hasClass( "ui-state-disabled" || // DEPRECATED as of 1.4.0 - remove after 1.4.0 release // only ui-state-disabled should be present thereafter $btn.hasClass( "ui-disabled" ) ) ) ) { $.mobile.removeActiveLinkClass( true ); $.mobile.activeClickedLink = $btn; $.mobile.activeClickedLink.addClass( $.mobile.activeBtnClass ); } }); // click routing - direct to HTTP or Ajax, accordingly $.mobile.document.bind( "click", function( event ) { if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) { return; } var link = findClosestLink( event.target ), $link = $( link ), //remove active link class if external (then it won't be there if you come back) httpCleanup = function() { window.setTimeout(function() { $.mobile.removeActiveLinkClass( true ); }, 200 ); }, baseUrl, href, useDefaultUrlHandling, isExternal, transition, reverse, role; // If a button was clicked, clean up the active class added by vclick above if ( $.mobile.activeClickedLink && $.mobile.activeClickedLink[ 0 ] === event.target.parentNode ) { httpCleanup(); } // If there is no link associated with the click or its not a left // click we want to ignore the click // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping // can be avoided if ( !link || event.which > 1 || !$link.jqmHijackable().length ) { return; } //if there's a data-rel=back attr, go back in history if ( $link.is( ":jqmData(rel='back')" ) ) { $.mobile.back(); return false; } baseUrl = $.mobile.getClosestBaseUrl( $link ); //get href, if defined, otherwise default to empty hash href = $.mobile.path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); //if ajax is disabled, exit early if ( !$.mobile.ajaxEnabled && !$.mobile.path.isEmbeddedPage( href ) ) { httpCleanup(); //use default click handling return; } // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) !== -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( $.mobile.path.isPath( href ) ) { //we have apath so make it the href we want to load. href = $.mobile.path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = $.mobile.path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ); // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( $.mobile.path.isExternal( href ) && !$.mobile.path.isPermittedCrossDomainRequest( documentUrl, href ) ); if ( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax transition = $link.jqmData( "transition" ); reverse = $link.jqmData( "direction" ) === "reverse" || // deprecated - remove by 1.0 $link.jqmData( "back" ); //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() { var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function() { var $link = $( this ), url = $link.attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } ); } }); }); // TODO ensure that the navigate binding in the content widget happens at the right time $.mobile.pageContainer.pagecontainer(); //set page min-heights to be device specific $.mobile.document.bind( "pageshow", $.mobile.resetActivePageHeight ); $.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight ); };//navreadyDeferred done callback $( function() { domreadyDeferred.resolve(); } ); $.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } ); })( jQuery ); (function( $, window, undefined ) { // TODO remove direct references to $.mobile and properties, we should // favor injection with params to the constructor $.mobile.Transition = function() { this.init.apply( this, arguments ); }; $.extend($.mobile.Transition.prototype, { toPreClass: " ui-page-pre-in", init: function( name, reverse, $to, $from ) { $.extend(this, { name: name, reverse: reverse, $to: $to, $from: $from, deferred: new $.Deferred() }); }, cleanFrom: function() { this.$from .removeClass( $.mobile.activePageClass + " out in reverse " + this.name ) .height( "" ); }, // NOTE overridden by child object prototypes, noop'd here as defaults beforeDoneIn: function() {}, beforeDoneOut: function() {}, beforeStartOut: function() {}, doneIn: function() { this.beforeDoneIn(); this.$to.removeClass( "out in reverse " + this.name ).height( "" ); this.toggleViewportClass(); // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition // This ensures we jump to that spot after the fact, if we aren't there already. if ( $.mobile.window.scrollTop() !== this.toScroll ) { this.scrollPage(); } if ( !this.sequential ) { this.$to.addClass( $.mobile.activePageClass ); } this.deferred.resolve( this.name, this.reverse, this.$to, this.$from, true ); }, doneOut: function( screenHeight, reverseClass, none, preventFocus ) { this.beforeDoneOut(); this.startIn( screenHeight, reverseClass, none, preventFocus ); }, hideIn: function( callback ) { // Prevent flickering in phonegap container: see comments at #4024 regarding iOS this.$to.css( "z-index", -10 ); callback.call( this ); this.$to.css( "z-index", "" ); }, scrollPage: function() { // By using scrollTo instead of silentScroll, we can keep things better in order // Just to be precautios, disable scrollstart listening like silentScroll would $.event.special.scrollstart.enabled = false; //if we are hiding the url bar or the page was previously scrolled scroll to hide or return to position if ( $.mobile.hideUrlBar || this.toScroll !== $.mobile.defaultHomeScroll ) { window.scrollTo( 0, this.toScroll ); } // reenable scrollstart listening like silentScroll would setTimeout( function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, startIn: function( screenHeight, reverseClass, none, preventFocus ) { this.hideIn(function() { this.$to.addClass( $.mobile.activePageClass + this.toPreClass ); // Send focus to page as it is now display: block if ( !preventFocus ) { $.mobile.focusPage( this.$to ); } // Set to page height this.$to.height( screenHeight + this.toScroll ); if ( !none ) { this.scrollPage(); } }); this.$to .removeClass( this.toPreClass ) .addClass( this.name + " in " + reverseClass ); if ( !none ) { this.$to.animationComplete( $.proxy(function() { this.doneIn(); }, this )); } else { this.doneIn(); } }, startOut: function( screenHeight, reverseClass, none ) { this.beforeStartOut( screenHeight, reverseClass, none ); // Set the from page's height and start it transitioning out // Note: setting an explicit height helps eliminate tiling in the transitions this.$from .height( screenHeight + $.mobile.window.scrollTop() ) .addClass( this.name + " out" + reverseClass ); }, toggleViewportClass: function() { $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + this.name ); }, transition: function() { // NOTE many of these could be calculated/recorded in the constructor, it's my // opinion that binding them as late as possible has value with regards to // better transitions with fewer bugs. Ie, it's not guaranteed that the // object will be created and transition will be run immediately after as // it is today. So we wait until transition is invoked to gather the following var reverseClass = this.reverse ? " reverse" : "", screenHeight = $.mobile.getScreenHeight(), maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth, none = !$.support.cssTransitions || !$.support.cssAnimations || maxTransitionOverride || !this.name || this.name === "none" || Math.max( $.mobile.window.scrollTop(), this.toScroll ) > $.mobile.getMaxScrollForTransition(); this.toScroll = $.mobile.navigate.history.getActive().lastScroll || $.mobile.defaultHomeScroll; this.toggleViewportClass(); if ( this.$from && !none ) { this.startOut( screenHeight, reverseClass, none ); } else { this.doneOut( screenHeight, reverseClass, none, true ); } return this.deferred.promise(); } }); })( jQuery, this ); (function( $ ) { $.mobile.SerialTransition = function() { this.init.apply(this, arguments); }; $.extend($.mobile.SerialTransition.prototype, $.mobile.Transition.prototype, { sequential: true, beforeDoneOut: function() { if ( this.$from ) { this.cleanFrom(); } }, beforeStartOut: function( screenHeight, reverseClass, none ) { this.$from.animationComplete($.proxy(function() { this.doneOut( screenHeight, reverseClass, none ); }, this )); } }); })( jQuery ); (function( $ ) { $.mobile.ConcurrentTransition = function() { this.init.apply(this, arguments); }; $.extend($.mobile.ConcurrentTransition.prototype, $.mobile.Transition.prototype, { sequential: false, beforeDoneIn: function() { if ( this.$from ) { this.cleanFrom(); } }, beforeStartOut: function( screenHeight, reverseClass, none ) { this.doneOut( screenHeight, reverseClass, none ); } }); })( jQuery ); (function( $ ) { // generate the handlers from the above var defaultGetMaxScrollForTransition = function() { return $.mobile.getScreenHeight() * 3; }; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { "sequential": $.mobile.SerialTransition, "simultaneous": $.mobile.ConcurrentTransition }; // Make our transition handler the public default. $.mobile.defaultTransitionHandler = $.mobile.transitionHandlers.sequential; $.mobile.transitionFallbacks = {}; // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified $.mobile._maybeDegradeTransition = function( transition ) { if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) { transition = $.mobile.transitionFallbacks[ transition ]; } return transition; }; // Set the getMaxScrollForTransition to default if no implementation was set by user $.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition; })( jQuery ); /* * fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flip = "fade"; })( jQuery, this ); /* * fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flow = "fade"; })( jQuery, this ); /* * fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.pop = "fade"; })( jQuery, this ); /* * fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Use the simultaneous transitions handler for slide transitions $.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous; // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slide = "fade"; })( jQuery, this ); /* * fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slidedown = "fade"; })( jQuery, this ); /* * fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slidefade = "fade"; })( jQuery, this ); /* * fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slideup = "fade"; })( jQuery, this ); /* * fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.turn = "fade"; })( jQuery, this ); (function( $, undefined ) { $.mobile.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: "text", tel: false, time: false, url: false, week: false }; // Backcompat remove in 1.5 $.mobile.page.prototype.options.degradeInputs = $.mobile.degradeInputs; // Auto self-init widgets $.mobile.degradeInputsWithin = function( target ) { target = $( target ); // Degrade inputs to avoid poorly implemented native functionality target.find( "input" ).not( $.mobile.page.prototype.keepNativeSelector() ).each(function() { var element = $( this ), type = this.getAttribute( "type" ), optType = $.mobile.degradeInputs[ type ] || "text", html, hasType, findstr, repstr; if ( $.mobile.degradeInputs[ type ] ) { html = $( "<div>" ).html( element.clone() ).html(); // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead hasType = html.indexOf( " type=" ) > -1; findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/; repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" ); element.replaceWith( html.replace( findstr, repstr ) ); } }); }; })( jQuery ); (function( $, window, undefined ) { $.widget( "mobile.page", $.mobile.page, { options: { // Accepts left, right and none closeBtn: "left", closeBtnText: "Close", overlayTheme: "a", corners: true, dialog: false }, _create: function() { this._super(); if ( this.options.dialog ) { $.extend( this, { _inner: this.element.children(), _headerCloseButton: null }); if ( !this.options.enhanced ) { this._setCloseBtn( this.options.closeBtn ); } } }, _enhance: function() { this._super(); // Class the markup for dialog styling and wrap interior if ( this.options.dialog ) { this.element.addClass( "ui-dialog" ) .wrapInner( $( "<div/>", { // ARIA role "role" : "dialog", "class" : "ui-dialog-contain ui-overlay-shadow" + ( this.options.corners ? " ui-corner-all" : "" ) })); } }, _setOptions: function( options ) { var closeButtonLocation, closeButtonText, currentOpts = this.options; if ( options.corners !== undefined ) { this._inner.toggleClass( "ui-corner-all", !!options.corners ); } if ( options.overlayTheme !== undefined ) { if ( $.mobile.activePage[ 0 ] === this.element[ 0 ] ) { currentOpts.overlayTheme = options.overlayTheme; this._handlePageBeforeShow(); } } if ( options.closeBtnText !== undefined ) { closeButtonLocation = currentOpts.closeBtn; closeButtonText = options.closeBtnText; } if ( options.closeBtn !== undefined ) { closeButtonLocation = options.closeBtn; } if ( closeButtonLocation ) { this._setCloseBtn( closeButtonLocation, closeButtonText ); } this._super( options ); }, _handlePageBeforeShow: function () { if ( this.options.overlayTheme && this.options.dialog ) { this.removeContainerBackground(); this.setContainerBackground( this.options.overlayTheme ); } else { this._super(); } }, _setCloseBtn: function( location, text ) { var dst, btn = this._headerCloseButton; // Sanitize value location = "left" === location ? "left" : "right" === location ? "right" : "none"; if ( "none" === location ) { if ( btn ) { btn.remove(); btn = null; } } else if ( btn ) { btn.removeClass( "ui-btn-left ui-btn-right" ).addClass( "ui-btn-" + location ); if ( text ) { btn.text( text ); } } else { dst = this._inner.find( ":jqmData(role='header')" ).first(); btn = $( "<a></a>", { "href": "#", "class": "ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-" + location }) .attr( "data-" + $.mobile.ns + "rel", "back" ) .text( text || this.options.closeBtnText || "" ) .prependTo( dst ); } this._headerCloseButton = btn; } }); })( jQuery, this ); (function( $, window, undefined ) { $.widget( "mobile.dialog", { options: { // Accepts left, right and none closeBtn: "left", closeBtnText: "Close", overlayTheme: "a", corners: true }, // Override the theme set by the page plugin on pageshow _handlePageBeforeShow: function() { this._isCloseable = true; if ( this.options.overlayTheme ) { this.element .page( "removeContainerBackground" ) .page( "setContainerBackground", this.options.overlayTheme ); } }, _handlePageBeforeHide: function() { this._isCloseable = false; }, // click and submit events: // - clicks and submits should use the closing transition that the dialog // opened with unless a data-transition is specified on the link/form // - if the click was on the close button, or the link has a data-rel="back" // it'll go back in history naturally _handleVClickSubmit: function( event ) { var attrs, $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ); if ( $target.length && !$target.jqmData( "transition" ) ) { attrs = {}; attrs[ "data-" + $.mobile.ns + "transition" ] = ( $.mobile.navigate.history.getActive() || {} )[ "transition" ] || $.mobile.defaultDialogTransition; attrs[ "data-" + $.mobile.ns + "direction" ] = "reverse"; $target.attr( attrs ); } }, _create: function() { var elem = this.element, opts = this.options; // Class the markup for dialog styling and wrap interior elem.addClass( "ui-dialog" ) .wrapInner( $( "<div/>", { // ARIA role "role" : "dialog", "class" : "ui-dialog-contain ui-overlay-shadow" + ( !!opts.corners ? " ui-corner-all" : "" ) })); $.extend( this, { _isCloseable: false, _inner: elem.children(), _headerCloseButton: null }); this._on( elem, { vclick: "_handleVClickSubmit", submit: "_handleVClickSubmit", pagebeforeshow: "_handlePageBeforeShow", pagebeforehide: "_handlePageBeforeHide" }); this._setCloseBtn( opts.closeBtn ); }, _setOptions: function( options ) { var closeButtonLocation, closeButtonText, currentOpts = this.options; if ( options.corners !== undefined ) { this._inner.toggleClass( "ui-corner-all", !!options.corners ); } if ( options.overlayTheme !== undefined ) { if ( $.mobile.activePage[ 0 ] === this.element[ 0 ] ) { currentOpts.overlayTheme = options.overlayTheme; this._handlePageBeforeShow(); } } if ( options.closeBtnText !== undefined ) { closeButtonLocation = currentOpts.closeBtn; closeButtonText = options.closeBtnText; } if ( options.closeBtn !== undefined ) { closeButtonLocation = options.closeBtn; } if ( closeButtonLocation ) { this._setCloseBtn( closeButtonLocation, closeButtonText ); } this._super( options ); }, _setCloseBtn: function( location, text ) { var dst, btn = this._headerCloseButton; // Sanitize value location = "left" === location ? "left" : "right" === location ? "right" : "none"; if ( "none" === location ) { if ( btn ) { btn.remove(); btn = null; } } else if ( btn ) { btn.removeClass( "ui-btn-left ui-btn-right" ).addClass( "ui-btn-" + location ); if ( text ) { btn.text( text ); } } else { dst = this._inner.find( ":jqmData(role='header')" ).first(); btn = $( "<a></a>", { "role": "button", "href": "#", "class": "ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-" + location }) .text( text || this.options.closeBtnText || "" ) .prependTo( dst ); this._on( btn, { click: "close" } ); } this._headerCloseButton = btn; }, // Close method goes back in history close: function() { var hist = $.mobile.navigate.history; if ( this._isCloseable ) { this._isCloseable = false; // If the hash listening is enabled and there is at least one preceding history // entry it's ok to go back. Initial pages with the dialog hash state are an example // where the stack check is necessary if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) { $.mobile.back(); } else { $.mobile.pageContainer.pagecontainer( "back" ); } } } }); })( jQuery, this ); (function( $, undefined ) { var rInitialLetter = /([A-Z])/g, // Construct iconpos class from iconpos value iconposClass = function( iconpos ) { return ( "ui-btn-icon-" + ( iconpos === null ? "left" : iconpos ) ); }; $.widget( "mobile.collapsible", { options: { enhanced: false, expandCueText: null, collapseCueText: null, collapsed: true, heading: "h1,h2,h3,h4,h5,h6,legend", collapsedIcon: null, expandedIcon: null, iconpos: null, theme: null, contentTheme: null, inset: null, corners: null, mini: null }, _create: function() { var elem = this.element, ui = { accordion: elem .closest( ":jqmData(role='collapsible-set')," + ":jqmData(role='collapsibleset')" + ( $.mobile.collapsibleset ? ", :mobile-collapsibleset" : "" ) ) .addClass( "ui-collapsible-set" ) }; this._ui = ui; this._renderedOptions = this._getOptions( this.options ); if ( this.options.enhanced ) { ui.heading = $( ".ui-collapsible-heading", this.element[ 0 ] ); ui.content = ui.heading.next(); ui.anchor = $( "a", ui.heading[ 0 ] ).first(); ui.status = ui.anchor.children( ".ui-collapsible-heading-status" ); } else { this._enhance( elem, ui ); } this._on( ui.heading, { "tap": function() { ui.heading.find( "a" ).first().addClass( $.mobile.activeBtnClass ); }, "click": function( event ) { this._handleExpandCollapse( !ui.heading.hasClass( "ui-collapsible-heading-collapsed" ) ); event.preventDefault(); event.stopPropagation(); } }); }, // Adjust the keys inside options for inherited values _getOptions: function( options ) { var key, accordion = this._ui.accordion, accordionWidget = this._ui.accordionWidget; // Copy options options = $.extend( {}, options ); if ( accordion.length && !accordionWidget ) { this._ui.accordionWidget = accordionWidget = accordion.data( "mobile-collapsibleset" ); } for ( key in options ) { // Retrieve the option value first from the options object passed in and, if // null, from the parent accordion or, if that's null too, or if there's no // parent accordion, then from the defaults. options[ key ] = ( options[ key ] != null ) ? options[ key ] : ( accordionWidget ) ? accordionWidget.options[ key ] : accordion.length ? $.mobile.getAttribute( accordion[ 0 ], key.replace( rInitialLetter, "-$1" ).toLowerCase() ): null; if ( null == options[ key ] ) { options[ key ] = $.mobile.collapsible.defaults[ key ]; } } return options; }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : prefix + value ) : "" ); }, _enhance: function( elem, ui ) { var iconclass, opts = this._renderedOptions, contentThemeClass = this._themeClassFromOption( "ui-body-", opts.contentTheme ); elem.addClass( "ui-collapsible " + ( opts.inset ? "ui-collapsible-inset " : "" ) + ( opts.inset && opts.corners ? "ui-corner-all " : "" ) + ( contentThemeClass ? "ui-collapsible-themed-content " : "" ) ); ui.originalHeading = elem.children( this.options.heading ).first(), ui.content = elem .wrapInner( "<div " + "class='ui-collapsible-content " + contentThemeClass + "'></div>" ) .children( ".ui-collapsible-content" ), ui.heading = ui.originalHeading; // Replace collapsibleHeading if it's a legend if ( ui.heading.is( "legend" ) ) { ui.heading = $( "<div role='heading'>"+ ui.heading.html() +"</div>" ); ui.placeholder = $( "<div><!-- placeholder for legend --></div>" ).insertBefore( ui.originalHeading ); ui.originalHeading.remove(); } iconclass = ( opts.collapsed ? ( opts.collapsedIcon ? "ui-icon-" + opts.collapsedIcon : "" ): ( opts.expandedIcon ? "ui-icon-" + opts.expandedIcon : "" ) ); ui.status = $( "<span class='ui-collapsible-heading-status'></span>" ); ui.anchor = ui.heading .detach() //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( ui.status ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a" ) .first() .addClass( "ui-btn " + ( iconclass ? iconclass + " " : "" ) + ( iconclass ? iconposClass( opts.iconpos ) + " " : "" ) + this._themeClassFromOption( "ui-btn-", opts.theme ) + " " + ( opts.mini ? "ui-mini " : "" ) ); //drop heading in before content ui.heading.insertBefore( ui.content ); this._handleExpandCollapse( this.options.collapsed ); return ui; }, refresh: function() { this._applyOptions( this.options ); this._renderedOptions = this._getOptions( this.options ); }, _applyOptions: function( options ) { var isCollapsed, newTheme, oldTheme, hasCorners, elem = this.element, currentOpts = this._renderedOptions, ui = this._ui, anchor = ui.anchor, status = ui.status, opts = this._getOptions( options ); // First and foremost we need to make sure the collapsible is in the proper // state, in case somebody decided to change the collapsed option at the // same time as another option if ( options.collapsed !== undefined ) { this._handleExpandCollapse( options.collapsed ); } isCollapsed = elem.hasClass( "ui-collapsible-collapsed" ); // Only options referring to the current state need to be applied right away // It is enough to store options covering the alternate in this.options. if ( isCollapsed ) { if ( opts.expandCueText !== undefined ) { status.text( opts.expandCueText ); } if ( opts.collapsedIcon !== undefined ) { if ( currentOpts.collapsedIcon ) { anchor.removeClass( "ui-icon-" + currentOpts.collapsedIcon ); } if ( opts.collapsedIcon ) { anchor.addClass( "ui-icon-" + opts.collapsedIcon ); } } } else { if ( opts.collapseCueText !== undefined ) { status.text( opts.collapseCueText ); } if ( opts.expandedIcon !== undefined ) { if ( currentOpts.expandedIcon ) { anchor.removeClass( "ui-icon-" + currentOpts.expandedIcon ); } if ( opts.expandedIcon ) { anchor.addClass( "ui-icon-" + opts.expandedIcon ); } } } if ( opts.iconpos !== undefined ) { anchor .removeClass( iconposClass( currentOpts.iconpos ) ) .addClass( iconposClass( opts.iconpos ) ); } if ( opts.theme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-btn-", currentOpts.theme ); newTheme = this._themeClassFromOption( "ui-btn-", opts.theme ); anchor.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.contentTheme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-body-", currentOpts.contentTheme ); newTheme = this._themeClassFromOption( "ui-body-", opts.contentTheme ); ui.content.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.inset !== undefined ) { elem.toggleClass( "ui-collapsible-inset", opts.inset ); hasCorners = !!( opts.inset && ( opts.corners || currentOpts.corners ) ); } if ( opts.corners !== undefined ) { hasCorners = !!( opts.corners && ( opts.inset || currentOpts.inset ) ); } if ( hasCorners !== undefined ) { elem.toggleClass( "ui-corner-all", hasCorners ); } if ( opts.mini !== undefined ) { anchor.toggleClass( "ui-mini", opts.mini ); } }, _setOptions: function( options ) { this._applyOptions( options ); this._super( options ); this._renderedOptions = this._getOptions( this.options ); }, _handleExpandCollapse: function( isCollapse ) { var opts = this._renderedOptions, ui = this._ui; ui.status.text( isCollapse ? opts.expandCueText : opts.collapseCueText ); ui.heading .toggleClass( "ui-collapsible-heading-collapsed", isCollapse ) .find( "a" ).first() .toggleClass( "ui-icon-" + opts.expandedIcon, !isCollapse ) // logic or cause same icon for expanded/collapsed state would remove the ui-icon-class .toggleClass( "ui-icon-" + opts.collapsedIcon, ( isCollapse || opts.expandedIcon === opts.collapsedIcon ) ) .removeClass( $.mobile.activeBtnClass ); this.element.toggleClass( "ui-collapsible-collapsed", isCollapse ); ui.content .toggleClass( "ui-collapsible-content-collapsed", isCollapse ) .attr( "aria-hidden", isCollapse ) .trigger( "updatelayout" ); this.options.collapsed = isCollapse; this._trigger( isCollapse ? "collapse" : "expand" ); }, expand: function() { this._handleExpandCollapse( false ); }, collapse: function() { this._handleExpandCollapse( true ); }, _destroy: function() { var ui = this._ui, opts = this.options; if ( opts.enhanced ) { return; } if ( ui.placeholder ) { ui.originalHeading.insertBefore( ui.placeholder ); ui.placeholder.remove(); ui.heading.remove(); } else { ui.status.remove(); ui.heading .removeClass( "ui-collapsible-heading ui-collapsible-heading-collapsed" ) .children() .contents() .unwrap(); } ui.anchor.contents().unwrap(); ui.content.contents().unwrap(); this.element .removeClass( "ui-collapsible ui-collapsible-collapsed " + "ui-collapsible-themed-content ui-collapsible-inset ui-corner-all" ); } }); // Defaults to be used by all instances of collapsible if per-instance values // are unset or if nothing is specified by way of inheritance from an accordion. // Note that this hash does not contain options "collapsed" or "heading", // because those are not inheritable. $.mobile.collapsible.defaults = { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsedIcon: "plus", contentTheme: "inherit", expandedIcon: "minus", iconpos: "left", inset: true, corners: true, theme: "inherit", mini: false }; })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.addFirstLastClasses = { _getVisibles: function( $els, create ) { var visibles; if ( create ) { visibles = $els.not( ".ui-screen-hidden" ); } else { visibles = $els.filter( ":visible" ); if ( visibles.length === 0 ) { visibles = $els.not( ".ui-screen-hidden" ); } } return visibles; }, _addFirstLastClasses: function( $els, $visibles, create ) { $els.removeClass( "ui-first-child ui-last-child" ); $visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" ); if ( !create ) { this.element.trigger( "updatelayout" ); } }, _removeFirstLastClasses: function( $els ) { $els.removeClass( "ui-first-child ui-last-child" ); } }; })( jQuery ); (function( $, undefined ) { var childCollapsiblesSelector = ":mobile-collapsible, " + $.mobile.collapsible.initSelector; $.widget( "mobile.collapsibleset", $.extend( { // The initSelector is deprecated as of 1.4.0. In 1.5.0 we will use // :jqmData(role='collapsibleset') which will allow us to get rid of the line // below altogether, because the autoinit will generate such an initSelector initSelector: ":jqmData(role='collapsible-set'),:jqmData(role='collapsibleset')", options: $.extend( { enhanced: false }, $.mobile.collapsible.defaults ), _handleCollapsibleExpand: function( event ) { var closestCollapsible = $( event.target ).closest( ".ui-collapsible" ); if ( closestCollapsible.parent().is( ":mobile-collapsibleset, :jqmData(role='collapsible-set')" ) ) { closestCollapsible .siblings( ".ui-collapsible:not(.ui-collapsible-collapsed)" ) .collapsible( "collapse" ); } }, _create: function() { var elem = this.element, opts = this.options; $.extend( this, { _classes: "" }); if ( !opts.enhanced ) { elem.addClass( "ui-collapsible-set " + this._themeClassFromOption( "ui-group-theme-", opts.theme ) + " " + ( opts.corners && opts.inset ? "ui-corner-all " : "" ) ); this.element.find( $.mobile.collapsible.initSelector ).collapsible(); } this._on( elem, { collapsibleexpand: "_handleCollapsibleExpand" } ); }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : prefix + value ) : "" ); }, _init: function() { this._refresh( true ); // Because the corners are handled by the collapsible itself and the default state is collapsed // That was causing https://github.com/jquery/jquery-mobile/issues/4116 this.element .children( childCollapsiblesSelector ) .filter( ":jqmData(collapsed='false')" ) .collapsible( "expand" ); }, _setOptions: function( options ) { var ret, hasCorners, elem = this.element, themeClass = this._themeClassFromOption( "ui-group-theme-", options.theme ); if ( themeClass ) { elem .removeClass( this._themeClassFromOption( "ui-group-theme-", this.options.theme ) ) .addClass( themeClass ); } if ( options.inset !== undefined ) { hasCorners = !!( options.inset && ( options.corners || this.options.corners ) ); } if ( options.corners !== undefined ) { hasCorners = !!( options.corners && ( options.inset || this.options.inset ) ); } if ( hasCorners !== undefined ) { elem.toggleClass( "ui-corner-all", hasCorners ); } ret = this._super( options ); this.element.children( ":mobile-collapsible" ).collapsible( "refresh" ); return ret; }, _destroy: function() { var el = this.element; this._removeFirstLastClasses( el.children( childCollapsiblesSelector ) ); el .removeClass( "ui-collapsible-set ui-corner-all " + this._themeClassFromOption( "ui-group-theme-", this.options.theme ) ) .children( ":mobile-collapsible" ) .collapsible( "destroy" ); }, _refresh: function( create ) { var collapsiblesInSet = this.element.children( childCollapsiblesSelector ); this.element.find( $.mobile.collapsible.initSelector ).not( ".ui-collapsible" ).collapsible(); this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create ); }, refresh: function() { this._refresh( false ); } }, $.mobile.behaviors.addFirstLastClasses ) ); })( jQuery ); (function( $, undefined ) { // Deprecated in 1.4 $.fn.fieldcontain = function(/* options */) { return this.addClass( "ui-field-contain" ); }; })( jQuery ); (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null }, options ), $kids = $this.children(), gridCols = { solo:1, a:2, b:3, c:4, d:5 }, grid = o.grid, iterator, letter; if ( !grid ) { if ( $kids.length <= 5 ) { for ( letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; $this.addClass( "ui-grid-duo" ); } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery ); (function( $, undefined ) { $.widget( "mobile.navbar", { options: { iconpos: "top", grid: null }, _create: function() { var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar" ) .attr( "role", "navigation" ) .find( "ul" ) .jqmEnhanceable() .grid({ grid: this.options.grid }); $navbtns .each( function() { var icon = $.mobile.getAttribute( this, "icon" ), theme = $.mobile.getAttribute( this, "theme" ), classes = "ui-btn"; if ( theme ) { classes += " ui-btn-" + theme; } if ( icon ) { classes += " ui-icon-" + icon + " ui-btn-icon-" + iconpos; } $( this ).addClass( classes ); }); $navbar.delegate( "a", "vclick", function( /* event */ ) { var activeBtn = $( this ); if ( !( activeBtn.hasClass( "ui-state-disabled" ) || // DEPRECATED as of 1.4.0 - remove after 1.4.0 release // only ui-state-disabled should be present thereafter activeBtn.hasClass( "ui-disabled" ) || activeBtn.hasClass( $.mobile.activeBtnClass ) ) ) { $navbtns.removeClass( $.mobile.activeBtnClass ); activeBtn.addClass( $.mobile.activeBtnClass ); // The code below is a workaround to fix #1181 $( document ).one( "pagehide", function() { activeBtn.removeClass( $.mobile.activeBtnClass ); }); } }); // Buttons in the navbar with ui-state-persist class should regain their active state before page show $navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() { $navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass ); }); } }); })( jQuery ); (function( $, undefined ) { var getAttr = $.mobile.getAttribute; $.widget( "mobile.listview", $.extend( { options: { theme: null, countTheme: null, /* Deprecated in 1.4 */ dividerTheme: null, icon: "carat-r", splitIcon: "carat-r", splitTheme: null, corners: true, shadow: true, inset: false }, _create: function() { var t = this, listviewClasses = ""; listviewClasses += t.options.inset ? " ui-listview-inset" : ""; if ( !!t.options.inset ) { listviewClasses += t.options.corners ? " ui-corner-all" : ""; listviewClasses += t.options.shadow ? " ui-shadow" : ""; } // create listview markup t.element.addClass( " ui-listview" + listviewClasses ); t.refresh( true ); }, // TODO: Remove in 1.5 _findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) { var dict = {}; dict[ lcName ] = dict[ ucName ] = true; while ( ele ) { if ( dict[ ele.nodeName ] ) { return ele; } ele = ele[ nextProp ]; } return null; }, // TODO: Remove in 1.5 _addThumbClasses: function( containers ) { var i, img, len = containers.length; for ( i = 0; i < len; i++ ) { img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) ); if ( img.length ) { $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.hasClass( "ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); } } }, _getChildrenByTagName: function( ele, lcName, ucName ) { var results = [], dict = {}; dict[ lcName ] = dict[ ucName ] = true; ele = ele.firstChild; while ( ele ) { if ( dict[ ele.nodeName ] ) { results.push( ele ); } ele = ele.nextSibling; } return $( results ); }, _beforeListviewRefresh: $.noop, _afterListviewRefresh: $.noop, refresh: function( create ) { var buttonClass, pos, numli, item, itemClass, itemTheme, itemIcon, icon, a, isDivider, startCount, newStartCount, value, last, splittheme, splitThemeClass, spliticon, altButtonClass, dividerTheme, li, o = this.options, $list = this.element, ol = !!$.nodeName( $list[ 0 ], "ol" ), start = $list.attr( "start" ), itemClassDict = {}, countBubbles = $list.find( ".ui-li-count" ), countTheme = getAttr( $list[ 0 ], "counttheme" ) || this.options.countTheme, countThemeClass = countTheme ? "ui-body-" + countTheme : "ui-body-inherit"; if ( o.theme ) { $list.addClass( "ui-group-theme-" + o.theme ); } // Check if a start attribute has been set while taking a value of 0 into account if ( ol && ( start || start === 0 ) ) { startCount = parseInt( start, 10 ) - 1; $list.css( "counter-reset", "listnumbering " + startCount ); } this._beforeListviewRefresh(); li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ); for ( pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = ""; if ( create || item[ 0 ].className.search( /\bui-li-static\b|\bui-li-divider\b/ ) < 0 ) { a = this._getChildrenByTagName( item[ 0 ], "a", "A" ); isDivider = ( getAttr( item[ 0 ], "role" ) === "list-divider" ); value = item.attr( "value" ); itemTheme = getAttr( item[ 0 ], "theme" ); if ( a.length && a[ 0 ].className.search( /\bui-btn\b/ ) < 0 && !isDivider ) { itemIcon = getAttr( item[ 0 ], "icon" ); icon = ( itemIcon === false ) ? false : ( itemIcon || o.icon ); // TODO: Remove in 1.5 together with links.js (links.js / .ui-link deprecated in 1.4) a.removeClass( "ui-link" ); buttonClass = "ui-btn"; if ( itemTheme ) { buttonClass += " ui-btn-" + itemTheme; } if ( a.length > 1 ) { itemClass = "ui-li-has-alt"; last = a.last(); splittheme = getAttr( last[ 0 ], "theme" ) || o.splitTheme || getAttr( item[ 0 ], "theme", true ); splitThemeClass = splittheme ? " ui-btn-" + splittheme : ""; spliticon = getAttr( last[ 0 ], "icon" ) || getAttr( item[ 0 ], "icon" ) || o.splitIcon; altButtonClass = "ui-btn ui-btn-icon-notext ui-icon-" + spliticon + splitThemeClass; last .attr( "title", $.trim( last.getEncodedText() ) ) .addClass( altButtonClass ) .empty(); } else if ( icon ) { buttonClass += " ui-btn-icon-right ui-icon-" + icon; } a.first().addClass( buttonClass ); } else if ( isDivider ) { dividerTheme = ( getAttr( item[ 0 ], "theme" ) || o.dividerTheme || o.theme ); itemClass = "ui-li-divider ui-bar-" + ( dividerTheme ? dividerTheme : "inherit" ); item.attr( "role", "heading" ); } else if ( a.length <= 0 ) { itemClass = "ui-li-static ui-body-" + ( itemTheme ? itemTheme : "inherit" ); } if ( ol && value ) { newStartCount = parseInt( value , 10 ) - 1; item.css( "counter-reset", "listnumbering " + newStartCount ); } } // Instead of setting item class directly on the list item // at this point in time, push the item into a dictionary // that tells us what class to set on it so we can do this after this // processing loop is finished. if ( !itemClassDict[ itemClass ] ) { itemClassDict[ itemClass ] = []; } itemClassDict[ itemClass ].push( item[ 0 ] ); } // Set the appropriate listview item classes on each list item. // The main reason we didn't do this // in the for-loop above is because we can eliminate per-item function overhead // by calling addClass() and children() once or twice afterwards. This // can give us a significant boost on platforms like WP7.5. for ( itemClass in itemClassDict ) { $( itemClassDict[ itemClass ] ).addClass( itemClass ); } countBubbles.each( function() { $( this ).closest( "li" ).addClass( "ui-li-has-count" ); }); if ( countThemeClass ) { countBubbles.addClass( countThemeClass ); } // Deprecated in 1.4. From 1.5 you have to add class ui-li-has-thumb or ui-li-has-icon to the LI. this._addThumbClasses( li ); this._addThumbClasses( li.find( ".ui-btn" ) ); this._afterListviewRefresh(); this._addFirstLastClasses( li, this._getVisibles( li, create ), create ); } }, $.mobile.behaviors.addFirstLastClasses ) ); })( jQuery ); (function( $, undefined ) { function defaultAutodividersSelector( elt ) { // look for the text in the given element var text = $.trim( elt.text() ) || null; if ( !text ) { return null; } // create the text for the divider (first uppercased letter) text = text.slice( 0, 1 ).toUpperCase(); return text; } $.widget( "mobile.listview", $.mobile.listview, { options: { autodividers: false, autodividersSelector: defaultAutodividersSelector }, _beforeListviewRefresh: function() { if ( this.options.autodividers ) { this._replaceDividers(); this._superApply( arguments ); } }, _replaceDividers: function() { var i, lis, li, dividerText, lastDividerText = null, list = this.element, divider; list.children( "li:jqmData(role='list-divider')" ).remove(); lis = list.children( "li" ); for ( i = 0; i < lis.length ; i++ ) { li = lis[ i ]; dividerText = this.options.autodividersSelector( $( li ) ); if ( dividerText && lastDividerText !== dividerText ) { divider = document.createElement( "li" ); divider.appendChild( document.createTextNode( dividerText ) ); divider.setAttribute( "data-" + $.mobile.ns + "role", "list-divider" ); li.parentNode.insertBefore( divider, li ); } lastDividerText = dividerText; } } }); })( jQuery ); (function( $, undefined ) { var rdivider = /(^|\s)ui-li-divider($|\s)/, rhidden = /(^|\s)ui-screen-hidden($|\s)/; $.widget( "mobile.listview", $.mobile.listview, { options: { hideDividers: false }, _afterListviewRefresh: function() { var items, idx, item, hideDivider = true; this._superApply( arguments ); if ( this.options.hideDividers ) { items = this._getChildrenByTagName( this.element[ 0 ], "li", "LI" ); for ( idx = items.length - 1 ; idx > -1 ; idx-- ) { item = items[ idx ]; if ( item.className.match( rdivider ) ) { if ( hideDivider ) { item.className = item.className + " ui-screen-hidden"; } hideDivider = true; } else { if ( !item.className.match( rhidden ) ) { hideDivider = false; } } } } } }); })( jQuery ); (function( $, undefined ) { $.mobile.nojs = function( target ) { $( ":jqmData(role='nojs')", target ).addClass( "ui-nojs" ); }; })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.formReset = { _handleFormReset: function() { this._on( this.element.closest( "form" ), { reset: function() { this._delay( "_reset" ); } }); } }; })( jQuery ); /* * "checkboxradio" plugin */ (function( $, undefined ) { $.widget( "mobile.checkboxradio", $.extend( { initSelector: "input:not( :jqmData(role='flipswitch' ) )[type='checkbox'],input[type='radio']:not( :jqmData(role='flipswitch' ))", options: { theme: "inherit", mini: false, wrapperClass: null, enhanced: false, iconpos: "left" }, _create: function() { var input = this.element, o = this.options, inheritAttr = function( input, dataAttr ) { return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr ); }, // NOTE: Windows Phone could not find the label through a selector // filter works though. parentLabel = input.closest( "label" ), label = parentLabel.length ? parentLabel : input .closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ) .find( "label" ) .filter( "[for='" + $.mobile.path.hashToSelector( input[0].id ) + "']" ) .first(), inputtype = input[0].type, checkedClass = "ui-" + inputtype + "-on", uncheckedClass = "ui-" + inputtype + "-off"; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } if ( this.element[0].disabled ) { this.options.disabled = true; } o.iconpos = inheritAttr( input, "iconpos" ) || label.attr( "data-" + $.mobile.ns + "iconpos" ) || o.iconpos, // Establish options o.mini = inheritAttr( input, "mini" ) || o.mini; // Expose for other methods $.extend( this, { input: input, label: label, parentLabel: parentLabel, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass }); if ( !this.options.enhanced ) { this._enhance(); } this._on( label, { vmouseover: "_handleLabelVMouseOver", vclick: "_handleLabelVClick" }); this._on( input, { vmousedown: "_cacheVals", vclick: "_handleInputVClick", focus: "_handleInputFocus", blur: "_handleInputBlur" }); this._handleFormReset(); this.refresh(); }, _enhance: function() { this.label.addClass( "ui-btn ui-corner-all"); if ( this.parentLabel.length > 0 ) { this.input.add( this.label ).wrapAll( this._wrapper() ); } else { //this.element.replaceWith( this.input.add( this.label ).wrapAll( this._wrapper() ) ); this.element.wrap( this._wrapper() ); this.element.parent().prepend( this.label ); } // Wrap the input + label in a div this._setOptions({ "theme": this.options.theme, "iconpos": this.options.iconpos, "mini": this.options.mini }); }, _wrapper: function() { return $( "<div class='" + ( this.options.wrapperClass ? this.options.wrapperClass : "" ) + " ui-" + this.inputtype + ( this.options.disabled ? " ui-state-disabled" : "" ) + "' ></div>" ); }, _handleInputFocus: function() { this.label.addClass( $.mobile.focusClass ); }, _handleInputBlur: function() { this.label.removeClass( $.mobile.focusClass ); }, _handleInputVClick: function() { var $this = this.element; // Adds checked attribute to checked input when keyboard is used if ( $this.is( ":checked" ) ) { $this.prop( "checked", true); this._getInputSet().not( $this ).prop( "checked", false ); } else { $this.prop( "checked", false ); } this._updateAll(); }, _handleLabelVMouseOver: function( event ) { if ( this.label.parent().hasClass( "ui-state-disabled" ) ) { event.stopPropagation(); } }, _handleLabelVClick: function( event ) { var input = this.element; if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } this._cacheVals(); input.prop( "checked", this.inputtype === "radio" && true || !input.prop( "checked" ) ); // trigger click handler's bound directly to the input as a substitute for // how label clicks behave normally in the browsers // TODO: it would be nice to let the browser's handle the clicks and pass them // through to the associate input. we can swallow that click at the parent // wrapper element level input.triggerHandler( "click" ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly this._getInputSet().not( input ).prop( "checked", false ); this._updateAll(); return false; }, _cacheVals: function() { this._getInputSet().each( function() { $( this ).attr("data-" + $.mobile.ns + "cacheVal", this.checked ); }); }, //returns either a set of radios with the same name attribute, or a single checkbox _getInputSet: function() { if ( this.inputtype === "checkbox" ) { return this.element; } return this.element.closest( "form, :jqmData(role='page'), :jqmData(role='dialog')" ) .find( "input[name='" + this.element[ 0 ].name + "'][type='" + this.inputtype + "']" ); }, _updateAll: function() { var self = this; this._getInputSet().each( function() { var $this = $( this ); if ( this.checked || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, _reset: function() { this.refresh(); }, // Is the widget supposed to display an icon? _hasIcon: function() { var controlgroup, controlgroupWidget, controlgroupConstructor = $.mobile.controlgroup; // If the controlgroup widget is defined ... if ( controlgroupConstructor ) { controlgroup = this.element.closest( ":mobile-controlgroup," + controlgroupConstructor.prototype.initSelector ); // ... and the checkbox is in a controlgroup ... if ( controlgroup.length > 0 ) { // ... look for a controlgroup widget instance, and ... controlgroupWidget = $.data( controlgroup[ 0 ], "mobile-controlgroup" ); // ... if found, decide based on the option value, ... return ( ( controlgroupWidget ? controlgroupWidget.options.type : // ... otherwise decide based on the "type" data attribute. controlgroup.attr( "data-" + $.mobile.ns + "type" ) ) !== "horizontal" ); } } // Normally, the widget displays an icon. return true; }, refresh: function() { var hasIcon = this._hasIcon(), isChecked = this.element[ 0 ].checked, active = $.mobile.activeBtnClass, iconposClass = "ui-btn-icon-" + this.options.iconpos, addClasses = [], removeClasses = []; if ( hasIcon ) { removeClasses.push( active ); addClasses.push( iconposClass ); } else { removeClasses.push( iconposClass ); ( isChecked ? addClasses : removeClasses ).push( active ); } if ( isChecked ) { addClasses.push( this.checkedClass ); removeClasses.push( this.uncheckedClass ); } else { addClasses.push( this.uncheckedClass ); removeClasses.push( this.checkedClass ); } this.label .addClass( addClasses.join( " " ) ) .removeClass( removeClasses.join( " " ) ); }, widget: function() { return this.label.parent(); }, _setOptions: function( options ) { var label = this.label, currentOptions = this.options, outer = this.widget(), hasIcon = this._hasIcon(); if ( options.disabled !== undefined ) { this.input.prop( "disabled", !!options.disabled ); outer.toggleClass( "ui-state-disabled", !!options.disabled ); } if ( options.mini !== undefined ) { outer.toggleClass( "ui-mini", !!options.mini ); } if ( options.theme !== undefined ) { label .removeClass( "ui-btn-" + currentOptions.theme ) .addClass( "ui-btn-" + options.theme ); } if ( options.wrapperClass !== undefined ) { outer .removeClass( currentOptions.wrapperClass ) .addClass( options.wrapperClass ); } if ( options.iconpos !== undefined && hasIcon ) { label.removeClass( "ui-btn-icon-" + currentOptions.iconpos ).addClass( "ui-btn-icon-" + options.iconpos ); } else if ( !hasIcon ) { label.removeClass( "ui-btn-icon-" + currentOptions.iconpos ); } this._super( options ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.button", { initSelector: "input[type='button'], input[type='submit'], input[type='reset']", options: { theme: null, icon: null, iconpos: "left", iconshadow: false, /* TODO: Deprecated in 1.4, remove in 1.5. */ corners: true, shadow: true, inline: null, mini: null, wrapperClass: null, enhanced: false }, _create: function() { if ( this.element.is( ":disabled" ) ) { this.options.disabled = true; } if ( !this.options.enhanced ) { this._enhance(); } $.extend( this, { wrapper: this.element.parent() }); this._on( { focus: function() { this.widget().addClass( $.mobile.focusClass ); }, blur: function() { this.widget().removeClass( $.mobile.focusClass ); } }); this.refresh( true ); }, _enhance: function() { this.element.wrap( this._button() ); }, _button: function() { var options = this.options, iconClasses = this._getIconClasses( this.options ); return $("<div class='ui-btn ui-input-btn" + ( options.wrapperClass ? " " + options.wrapperClass : "" ) + ( options.theme ? " ui-btn-" + options.theme : "" ) + ( options.corners ? " ui-corner-all" : "" ) + ( options.shadow ? " ui-shadow" : "" ) + ( options.inline ? " ui-btn-inline" : "" ) + ( options.mini ? " ui-mini" : "" ) + ( options.disabled ? " ui-state-disabled" : "" ) + ( iconClasses ? ( " " + iconClasses ) : "" ) + "' >" + this.element.val() + "</div>" ); }, widget: function() { return this.wrapper; }, _destroy: function() { this.element.insertBefore( this.button ); this.button.remove(); }, _getIconClasses: function( options ) { return ( options.icon ? ( "ui-icon-" + options.icon + ( options.iconshadow ? " ui-shadow-icon" : "" ) + /* TODO: Deprecated in 1.4, remove in 1.5. */ " ui-btn-icon-" + options.iconpos ) : "" ); }, _setOptions: function( options ) { var outer = this.widget(); if ( options.theme !== undefined ) { outer .removeClass( this.options.theme ) .addClass( "ui-btn-" + options.theme ); } if ( options.corners !== undefined ) { outer.toggleClass( "ui-corner-all", options.corners ); } if ( options.shadow !== undefined ) { outer.toggleClass( "ui-shadow", options.shadow ); } if ( options.inline !== undefined ) { outer.toggleClass( "ui-btn-inline", options.inline ); } if ( options.mini !== undefined ) { outer.toggleClass( "ui-mini", options.mini ); } if ( options.disabled !== undefined ) { this.element.prop( "disabled", options.disabled ); outer.toggleClass( "ui-state-disabled", options.disabled ); } if ( options.icon !== undefined || options.iconshadow !== undefined || /* TODO: Deprecated in 1.4, remove in 1.5. */ options.iconpos !== undefined ) { outer .removeClass( this._getIconClasses( this.options ) ) .addClass( this._getIconClasses( $.extend( {}, this.options, options ) ) ); } this._super( options ); }, refresh: function( create ) { if ( this.options.icon && this.options.iconpos === "notext" && this.element.attr( "title" ) ) { this.element.attr( "title", this.element.val() ); } if ( !create ) { var originalElement = this.element.detach(); $( this.wrapper ).text( this.element.val() ).append( originalElement ); } } }); })( jQuery ); (function( $ ) { var meta = $( "meta[name=viewport]" ), initialContent = meta.attr( "content" ), disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no", enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes", disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent ); $.mobile.zoom = $.extend( {}, { enabled: !disabledInitially, locked: false, disable: function( lock ) { if ( !disabledInitially && !$.mobile.zoom.locked ) { meta.attr( "content", disabledZoom ); $.mobile.zoom.enabled = false; $.mobile.zoom.locked = lock || false; } }, enable: function( unlock ) { if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) { meta.attr( "content", enabledZoom ); $.mobile.zoom.enabled = true; $.mobile.zoom.locked = false; } }, restore: function() { if ( !disabledInitially ) { meta.attr( "content", initialContent ); $.mobile.zoom.enabled = true; } } }); }( jQuery )); (function( $, undefined ) { $.widget( "mobile.textinput", { initSelector: "input[type='text']," + "input[type='search']," + ":jqmData(type='search')," + "input[type='number']," + ":jqmData(type='number')," + "input[type='password']," + "input[type='email']," + "input[type='url']," + "input[type='tel']," + "textarea," + "input[type='time']," + "input[type='date']," + "input[type='month']," + "input[type='week']," + "input[type='datetime']," + "input[type='datetime-local']," + "input[type='color']," + "input:not([type])," + "input[type='file']", options: { theme: null, corners: true, mini: false, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, wrapperClass: "", enhanced: false }, _create: function() { var options = this.options, isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ), isTextarea = this.element[ 0 ].tagName === "TEXTAREA", isRange = this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='range']" ), inputNeedsWrap = ( (this.element.is( "input" ) || this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='search']" ) ) && !isRange ); if ( this.element.prop( "disabled" ) ) { options.disabled = true; } $.extend( this, { classes: this._classesFromOptions(), isSearch: isSearch, isTextarea: isTextarea, isRange: isRange, inputNeedsWrap: inputNeedsWrap }); this._autoCorrect(); if ( !options.enhanced ) { this._enhance(); } this._on( { "focus": "_handleFocus", "blur": "_handleBlur" }); }, refresh: function() { this.setOptions({ "disabled" : this.element.is( ":disabled" ) }); }, _enhance: function() { var elementClasses = []; if ( this.isTextarea ) { elementClasses.push( "ui-input-text" ); } if ( this.isTextarea || this.isRange ) { elementClasses.push( "ui-shadow-inset" ); } //"search" and "text" input widgets if ( this.inputNeedsWrap ) { this.element.wrap( this._wrap() ); } else { elementClasses = elementClasses.concat( this.classes ); } this.element.addClass( elementClasses.join( " " ) ); }, widget: function() { return ( this.inputNeedsWrap ) ? this.element.parent() : this.element; }, _classesFromOptions: function() { var options = this.options, classes = []; classes.push( "ui-body-" + ( ( options.theme === null ) ? "inherit" : options.theme ) ); if ( options.corners ) { classes.push( "ui-corner-all" ); } if ( options.mini ) { classes.push( "ui-mini" ); } if ( options.disabled ) { classes.push( "ui-state-disabled" ); } if ( options.wrapperClass ) { classes.push( options.wrapperClass ); } return classes; }, _wrap: function() { return $( "<div class='" + ( this.isSearch ? "ui-input-search " : "ui-input-text " ) + this.classes.join( " " ) + " " + "ui-shadow-inset'></div>" ); }, _autoCorrect: function() { // XXX: Temporary workaround for issue 785 (Apple bug 8910589). // Turn off autocorrect and autocomplete on non-iOS 5 devices // since the popup they use can't be dismissed by the user. Note // that we test for the presence of the feature by looking for // the autocorrect property on the input element. We currently // have no test for iOS 5 or newer so we're temporarily using // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. // - jblas if ( typeof this.element[0].autocorrect !== "undefined" && !$.support.touchOverflow ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. this.element[0].setAttribute( "autocorrect", "off" ); this.element[0].setAttribute( "autocomplete", "off" ); } }, _handleBlur: function() { this.widget().removeClass( $.mobile.focusClass ); if ( this.options.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }, _handleFocus: function() { // In many situations, iOS will zoom into the input upon tap, this // prevents that from happening if ( this.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } this.widget().addClass( $.mobile.focusClass ); }, _setOptions: function ( options ) { var outer = this.widget(); this._super( options ); if ( !( options.disabled === undefined && options.mini === undefined && options.corners === undefined && options.theme === undefined && options.wrapperClass === undefined ) ) { outer.removeClass( this.classes.join( " " ) ); this.classes = this._classesFromOptions(); outer.addClass( this.classes.join( " " ) ); } if ( options.disabled !== undefined ) { this.element.prop( "disabled", !!options.disabled ); } }, _destroy: function() { if ( this.options.enhanced ) { return; } if ( this.inputNeedsWrap ) { this.element.unwrap(); } this.element.removeClass( "ui-input-text " + this.classes.join( " " ) ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.slider", $.extend( { initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')", widgetEventPrefix: "slide", options: { theme: null, trackTheme: null, corners: true, mini: false, highlight: false }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, trackTheme = this.options.trackTheme || $.mobile.getAttribute( control[ 0 ], "theme" ), trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", cornerClass = ( this.options.corners || control.jqmData( "corners" ) ) ? " ui-corner-all" : "", miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "", cType = control[ 0 ].nodeName.toLowerCase(), isToggleSwitch = ( cType === "select" ), isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ), selectClass = ( isToggleSwitch ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), $label = $( "[for='" + controlID + "']" ), labelID = $label.attr( "id" ) || controlID + "-label", min = !isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0, max = !isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), domHandle = document.createElement( "a" ), handle = $( domHandle ), domSlider = document.createElement( "div" ), slider = $( domSlider ), valuebg = this.options.highlight && !isToggleSwitch ? (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; return $( bg ).prependTo( slider ); })() : false, options, wrapper, j, length, i, optionsCount, origTabIndex, side, activeClass, sliderImg; $label.attr( "id", labelID ); this.isToggleSwitch = isToggleSwitch; domHandle.setAttribute( "href", "#" ); domSlider.setAttribute( "role", "application" ); domSlider.className = [ this.isToggleSwitch ? "ui-slider ui-slider-track ui-shadow-inset " : "ui-slider-track ui-shadow-inset ", selectClass, trackThemeClass, cornerClass, miniClass ].join( "" ); domHandle.className = "ui-slider-handle"; domSlider.appendChild( domHandle ); handle.attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": this._value(), "aria-valuetext": this._value(), "title": this._value(), "aria-labelledby": labelID }); $.extend( this, { slider: slider, handle: handle, control: control, type: cType, step: step, max: max, min: min, valuebg: valuebg, isRangeslider: isRangeslider, dragging: false, beforeStart: null, userModified: false, mouseMoved: false }); if ( isToggleSwitch ) { // TODO: restore original tabindex (if any) in a destroy method origTabIndex = control.attr( "tabindex" ); if ( origTabIndex ) { handle.attr( "tabindex", origTabIndex ); } control.attr( "tabindex", "-1" ).focus(function() { $( this ).blur(); handle.focus(); }); wrapper = document.createElement( "div" ); wrapper.className = "ui-slider-inneroffset"; for ( j = 0, length = domSlider.childNodes.length; j < length; j++ ) { wrapper.appendChild( domSlider.childNodes[j] ); } domSlider.appendChild( wrapper ); // slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); // make the handle move with a smooth transition handle.addClass( "ui-slider-handle-snapping" ); options = control.find( "option" ); for ( i = 0, optionsCount = options.length; i < optionsCount; i++ ) { side = !i ? "b" : "a"; activeClass = !i ? "" : " " + $.mobile.activeBtnClass; sliderImg = document.createElement( "span" ); sliderImg.className = [ "ui-slider-label ui-slider-label-", side, activeClass ].join( "" ); sliderImg.setAttribute( "role", "img" ); sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) ); $( sliderImg ).prependTo( slider ); } self._labels = $( ".ui-slider-label", slider ); } // monitor the input for updated values control.addClass( isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" ); this._on( control, { "change": "_controlChange", "keyup": "_controlKeyup", "blur": "_controlBlur", "vmouseup": "_controlVMouseUp" }); slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) ) .bind( "vclick", false ); // We have to instantiate a new function object for the unbind to work properly // since the method itself is defined in the prototype (causing it to unbind everything) this._on( document, { "vmousemove": "_preventDocumentDrag" }); this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" }); slider.insertAfter( control ); // wrap in a div for styling purposes if ( !isToggleSwitch && !isRangeslider ) { wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>"; control.add( slider ).wrapAll( wrapper ); } // bind the handle event callbacks and set the context to the widget instance this._on( this.handle, { "vmousedown": "_handleVMouseDown", "keydown": "_handleKeydown", "keyup": "_handleKeyup" }); this.handle.bind( "vclick", false ); this._handleFormReset(); this.refresh( undefined, undefined, true ); }, _setOptions: function( options ) { if ( options.theme !== undefined ) { this._setTheme( options.theme ); } if ( options.trackTheme !== undefined ) { this._setTrackTheme( options.trackTheme ); } if ( options.corners !== undefined ) { this._setCorners( options.corners ); } if ( options.mini !== undefined ) { this._setMini( options.mini ); } if ( options.highlight !== undefined ) { this._setHighlight( options.highlight ); } if ( options.disabled !== undefined ) { this._setDisabled( options.disabled ); } this._super( options ); }, _controlChange: function( event ) { // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again if ( this._trigger( "controlchange", event ) === false ) { return false; } if ( !this.mouseMoved ) { this.refresh( this._value(), true ); } }, _controlKeyup: function(/* event */) { // necessary? this.refresh( this._value(), true, true ); }, _controlBlur: function(/* event */) { this.refresh( this._value(), true ); }, // it appears the clicking the up and down buttons in chrome on // range/number inputs doesn't trigger a change until the field is // blurred. Here we check thif the value has changed and refresh _controlVMouseUp: function(/* event */) { this._checkedRefresh(); }, // NOTE force focus on handle _handleVMouseDown: function(/* event */) { this.handle.focus(); }, _handleKeydown: function( event ) { var index = this._value(); if ( this.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; this.handle.addClass( "ui-state-active" ); /* TODO: We don't use this class for styling. Do we need to add it? */ } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: this.refresh( this.min ); break; case $.mobile.keyCode.END: this.refresh( this.max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: this.refresh( index + this.step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: this.refresh( index - this.step ); break; } }, // remove active mark _handleKeyup: function(/* event */) { if ( this._keySliding ) { this._keySliding = false; this.handle.removeClass( "ui-state-active" ); /* See comment above. */ } }, _sliderVMouseDown: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this.options.disabled || !( event.which === 1 || event.which === 0 || event.which === undefined ) ) { return false; } if ( this._trigger( "beforestart", event ) === false ) { return false; } this.dragging = true; this.userModified = false; this.mouseMoved = false; if ( this.isToggleSwitch ) { this.beforeStart = this.element[0].selectedIndex; } this.refresh( event ); this._trigger( "start" ); return false; }, _sliderVMouseUp: function() { if ( this.dragging ) { this.dragging = false; if ( this.isToggleSwitch ) { // make the handle move with a smooth transition this.handle.addClass( "ui-slider-handle-snapping" ); if ( this.mouseMoved ) { // this is a drag, change the value only if user dragged enough if ( this.userModified ) { this.refresh( this.beforeStart === 0 ? 1 : 0 ); } else { this.refresh( this.beforeStart ); } } else { // this is just a click, change the value this.refresh( this.beforeStart === 0 ? 1 : 0 ); } } this.mouseMoved = false; this._trigger( "stop" ); return false; } }, _preventDocumentDrag: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this._trigger( "drag", event ) === false) { return false; } if ( this.dragging && !this.options.disabled ) { // this.mouseMoved must be updated before refresh() because it will be used in the control "change" event this.mouseMoved = true; if ( this.isToggleSwitch ) { // make the handle move in sync with the mouse this.handle.removeClass( "ui-slider-handle-snapping" ); } this.refresh( event ); // only after refresh() you can calculate this.userModified this.userModified = this.beforeStart !== this.element[0].selectedIndex; return false; } }, _checkedRefresh: function() { if ( this.value !== this._value() ) { this.refresh( this._value() ); } }, _value: function() { return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ; }, _reset: function() { this.refresh( undefined, false, true ); }, refresh: function( val, isfromControl, preventInputUpdate ) { // NOTE: we don't return here because we want to support programmatic // alteration of the input value, which should still update the slider var self = this, parentTheme = $.mobile.getAttribute( this.element[ 0 ], "theme" ), theme = this.options.theme || parentTheme, themeClass = theme ? " ui-btn-" + theme : "", trackTheme = this.options.trackTheme || parentTheme, trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", cornerClass = this.options.corners ? " ui-corner-all" : "", miniClass = this.options.mini ? " ui-mini" : "", left, width, data, tol, pxStep, percent, control, isInput, optionElements, min, max, step, newval, valModStep, alignValue, percentPerStep, handlePercent, aPercent, bPercent, valueChanged; self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch ui-slider-track ui-shadow-inset" : "ui-slider-track ui-shadow-inset", trackThemeClass, cornerClass, miniClass ].join( "" ); if ( this.options.disabled || this.element.prop( "disabled" ) ) { this.disable(); } // set the stored value for comparison later this.value = this._value(); if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) { this.valuebg = (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; return $( bg ).prependTo( self.slider ); })(); } this.handle.addClass( "ui-btn" + themeClass + " ui-shadow" ); control = this.element; isInput = !this.isToggleSwitch; optionElements = isInput ? [] : control.find( "option" ); min = isInput ? parseFloat( control.attr( "min" ) ) : 0; max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1; step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1; if ( typeof val === "object" ) { data = val; // a slight tolerance helped get to the ends of the slider tol = 8; left = this.slider.offset().left; width = this.slider.width(); pxStep = width/((max-min)/step); if ( !this.dragging || data.pageX < left - tol || data.pageX > left + width + tol ) { return; } if ( pxStep > 1 ) { percent = ( ( data.pageX - left ) / width ) * 100; } else { percent = Math.round( ( ( data.pageX - left ) / width ) * 100 ); } } else { if ( val == null ) { val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } newval = ( percent / 100 ) * ( max - min ) + min; //from jQuery UI slider, the following source will round to the nearest step valModStep = ( newval - min ) % step; alignValue = newval - valModStep; if ( Math.abs( valModStep ) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } percentPerStep = 100/((max-min)/step); // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see jQueryUI: #4124) newval = parseFloat( alignValue.toFixed(5) ); if ( typeof pxStep === "undefined" ) { pxStep = width / ( (max-min) / step ); } if ( pxStep > 1 && isInput ) { percent = ( newval - min ) * percentPerStep * ( 1 / step ); } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } this.handle.css( "left", percent + "%" ); this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) ); this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); if ( this.valuebg ) { this.valuebg.css( "width", percent + "%" ); } // drag the label widths if ( this._labels ) { handlePercent = this.handle.width() / this.slider.width() * 100; aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100; bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 ); this._labels.each(function() { var ab = $( this ).hasClass( "ui-slider-label-a" ); $( this ).width( ( ab ? aPercent : bPercent ) + "%" ); }); } if ( !preventInputUpdate ) { valueChanged = false; // update control"s value if ( isInput ) { valueChanged = control.val() !== newval; control.val( newval ); } else { valueChanged = control[ 0 ].selectedIndex !== newval; control[ 0 ].selectedIndex = newval; } if ( this._trigger( "beforechange", val ) === false) { return false; } if ( !isfromControl && valueChanged ) { control.trigger( "change" ); } } }, _setHighlight: function( value ) { value = !!value; if ( value ) { this.options.highlight = !!value; this.refresh(); } else if ( this.valuebg ) { this.valuebg.remove(); this.valuebg = false; } }, _setTheme: function( value ) { this.handle .removeClass( "ui-btn-" + this.options.theme ) .addClass( "ui-btn-" + value ); var currentTheme = this.options.theme ? this.options.theme : "inherit", newTheme = value ? value : "inherit"; this.control .removeClass( "ui-body-" + currentTheme ) .addClass( "ui-body-" + newTheme ); }, _setTrackTheme: function( value ) { var currentTrackTheme = this.options.trackTheme ? this.options.trackTheme : "inherit", newTrackTheme = value ? value : "inherit"; this.slider .removeClass( "ui-body-" + currentTrackTheme ) .addClass( "ui-body-" + newTrackTheme ); }, _setMini: function( value ) { value = !!value; if ( !this.isToggleSwitch && !this.isRangeslider ) { this.slider.parent().toggleClass( "ui-mini", value ); this.element.toggleClass( "ui-mini", value ); } this.slider.toggleClass( "ui-mini", value ); }, _setCorners: function( value ) { this.slider.toggleClass( "ui-corner-all", value ); if ( !this.isToggleSwitch ) { this.control.toggleClass( "ui-corner-all", value ); } }, _setDisabled: function( value ) { value = !!value; this.element.prop( "disabled", value ); this.slider .toggleClass( "ui-state-disabled", value ) .attr( "aria-disabled", value ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { var popup; function getPopup() { if ( !popup ) { popup = $( "<div></div>", { "class": "ui-slider-popup ui-shadow ui-corner-all" }); } return popup.clone(); } $.widget( "mobile.slider", $.mobile.slider, { options: { popupEnabled: false, showValue: false }, _create: function() { this._super(); $.extend( this, { _currentValue: null, _popup: null, _popupVisible: false }); this._setOption( "popupEnabled", this.options.popupEnabled ); this._on( this.handle, { "vmousedown" : "_showPopup" } ); this._on( this.slider.add( this.document ), { "vmouseup" : "_hidePopup" } ); this._refresh(); }, // position the popup centered 5px above the handle _positionPopup: function() { var dstOffset = this.handle.offset(); this._popup.offset( { left: dstOffset.left + ( this.handle.width() - this._popup.width() ) / 2, top: dstOffset.top - this._popup.outerHeight() - 5 }); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "showValue" ) { this.handle.html( value && !this.options.mini ? this._value() : "" ); } else if ( key === "popupEnabled" ) { if ( value && !this._popup ) { this._popup = getPopup() .addClass( "ui-body-" + ( this.options.theme || "a" ) ) .hide() .insertBefore( this.element ); } } }, // show value on the handle and in popup refresh: function() { this._super.apply( this, arguments ); this._refresh(); }, _refresh: function() { var o = this.options, newValue; if ( o.popupEnabled ) { // remove the title attribute from the handle (which is // responsible for the annoying tooltip); NB we have // to do it here as the jqm slider sets it every time // the slider's value changes :( this.handle.removeAttr( "title" ); } newValue = this._value(); if ( newValue === this._currentValue ) { return; } this._currentValue = newValue; if ( o.popupEnabled && this._popup ) { this._positionPopup(); this._popup.html( newValue ); } else if ( o.showValue && !this.options.mini ) { this.handle.html( newValue ); } }, _showPopup: function() { if ( this.options.popupEnabled && !this._popupVisible ) { this.handle.html( "" ); this._popup.show(); this._positionPopup(); this._popupVisible = true; } }, _hidePopup: function() { var o = this.options; if ( o.popupEnabled && this._popupVisible ) { if ( o.showValue && !o.mini ) { this.handle.html( this._value() ); } this._popup.hide(); this._popupVisible = false; } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.flipswitch", $.extend({ options: { onText: "On", offText: "Off", theme: null, enhanced: false, wrapperClass: null, corners: true, mini: false }, _create: function() { if ( !this.options.enhanced ) { this._enhance(); } else { $.extend( this, { flipswitch: this.element.parent(), on: this.element.find( ".ui-flipswitch-on" ).eq( 0 ), off: this.element.find( ".ui-flipswitch-off" ).eq(0), type: this.element.get( 0 ).tagName }); } this._handleFormReset(); // Transfer tabindex to "on" element and make input unfocusable this._originalTabIndex = this.element.attr( "tabindex" ); if ( this._originalTabIndex != null ) { this.on.attr( "tabindex", this._originalTabIndex ); } this.element.attr( "tabindex", "-1" ); this._on({ "focus" : "_handleInputFocus" }); if ( this.element.is( ":disabled" ) ) { this._setOptions({ "disabled": true }); } this._on( this.flipswitch, { "click": "_toggle", "swipeleft": "_left", "swiperight": "_right" }); this._on( this.on, { "keydown": "_keydown" }); this._on( { "change": "refresh" }); }, _handleInputFocus: function() { this.on.focus(); }, widget: function() { return this.flipswitch; }, _left: function() { this.flipswitch.removeClass( "ui-flipswitch-active" ); if ( this.type === "SELECT" ) { this.element.get( 0 ).selectedIndex = 0; } else { this.element.prop( "checked", false ); } this.element.trigger( "change" ); }, _right: function() { this.flipswitch.addClass( "ui-flipswitch-active" ); if ( this.type === "SELECT" ) { this.element.get( 0 ).selectedIndex = 1; } else { this.element.prop( "checked", true ); } this.element.trigger( "change" ); }, _enhance: function() { var flipswitch = $( "<div>" ), options = this.options, element = this.element, theme = options.theme ? options.theme : "inherit", // The "on" button is an anchor so it's focusable on = $( "<a></a>", { "href": "#" }), off = $( "<span></span>" ), type = element.get( 0 ).tagName, onText = ( type === "INPUT" ) ? options.onText : element.find( "option" ).eq( 1 ).text(), offText = ( type === "INPUT" ) ? options.offText : element.find( "option" ).eq( 0 ).text(); on .addClass( "ui-flipswitch-on ui-btn ui-shadow ui-btn-inherit" ) .text( onText ); off .addClass( "ui-flipswitch-off" ) .text( offText ); flipswitch .addClass( "ui-flipswitch ui-shadow-inset " + "ui-bar-" + theme + " " + ( options.wrapperClass ? options.wrapperClass : "" ) + " " + ( ( element.is( ":checked" ) || element .find( "option" ) .eq( 1 ) .is( ":selected" ) ) ? "ui-flipswitch-active" : "" ) + ( element.is(":disabled") ? " ui-state-disabled": "") + ( options.corners ? " ui-corner-all": "" ) + ( options.mini ? " ui-mini": "" ) ) .append( on, off ); element .addClass( "ui-flipswitch-input" ) .after( flipswitch ) .appendTo( flipswitch ); $.extend( this, { flipswitch: flipswitch, on: on, off: off, type: type }); }, _reset: function() { this.refresh(); }, refresh: function() { var direction, existingDirection = this.flipswitch.hasClass( "ui-flipswitch-active" ) ? "_right" : "_left"; if ( this.type === "SELECT" ) { direction = ( this.element.get( 0 ).selectedIndex > 0 ) ? "_right": "_left"; } else { direction = this.element.prop( "checked" ) ? "_right": "_left"; } if ( direction !== existingDirection ) { this[ direction ](); } }, _toggle: function() { var direction = this.flipswitch.hasClass( "ui-flipswitch-active" ) ? "_left" : "_right"; this[ direction ](); }, _keydown: function( e ) { if ( e.which === $.mobile.keyCode.LEFT ) { this._left(); } else if ( e.which === $.mobile.keyCode.RIGHT ) { this._right(); } else if ( e.which === $.mobile.keyCode.SPACE ) { this._toggle(); e.preventDefault(); } }, _setOptions: function( options ) { if ( options.theme !== undefined ) { var currentTheme = options.theme ? options.theme : "inherit", newTheme = options.theme ? options.theme : "inherit"; this.widget() .removeClass( "ui-bar-" + currentTheme ) .addClass( "ui-bar-" + newTheme ); } if ( options.onText !== undefined ) { this.on.text( options.onText ); } if ( options.offText !== undefined ) { this.off.text( options.offText ); } if ( options.disabled !== undefined ) { this.widget().toggleClass( "ui-state-disabled", options.disabled ); } if ( options.mini !== undefined ) { this.widget().toggleClass( "ui-mini", options.mini ); } if ( options.corners !== undefined ) { this.widget().toggleClass( "ui-corner-all", options.corners ); } this._super( options ); }, _destroy: function() { if ( this.options.enhanced ) { return; } if ( this._originalTabIndex != null ) { this.element.attr( "tabindex", this._originalTabIndex ); } else { this.element.removeAttr( "tabindex" ); } this.on.remove(); this.off.remove(); this.element.unwrap(); this.flipswitch.remove(); this.removeClass( "ui-flipswitch-input" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.rangeslider", $.extend( { options: { theme: null, trackTheme: null, corners: true, mini: false, highlight: true }, _create: function() { var $el = this.element, elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider", _inputFirst = $el.find( "input" ).first(), _inputLast = $el.find( "input" ).last(), _label = $el.find( "label" ).first(), _sliderWidgetFirst = $.data( _inputFirst.get( 0 ), "mobile-slider" ) || $.data( _inputFirst.slider().get( 0 ), "mobile-slider" ), _sliderWidgetLast = $.data( _inputLast.get(0), "mobile-slider" ) || $.data( _inputLast.slider().get( 0 ), "mobile-slider" ), _sliderFirst = _sliderWidgetFirst.slider, _sliderLast = _sliderWidgetLast.slider, firstHandle = _sliderWidgetFirst.handle, _sliders = $( "<div class='ui-rangeslider-sliders' />" ).appendTo( $el ); _inputFirst.addClass( "ui-rangeslider-first" ); _inputLast.addClass( "ui-rangeslider-last" ); $el.addClass( elClass ); _sliderFirst.appendTo( _sliders ); _sliderLast.appendTo( _sliders ); _label.insertBefore( $el ); firstHandle.prependTo( _sliderLast ); $.extend( this, { _inputFirst: _inputFirst, _inputLast: _inputLast, _sliderFirst: _sliderFirst, _sliderLast: _sliderLast, _label: _label, _targetVal: null, _sliderTarget: false, _sliders: _sliders, _proxy: false }); this.refresh(); this._on( this.element.find( "input.ui-slider-input" ), { "slidebeforestart": "_slidebeforestart", "slidestop": "_slidestop", "slidedrag": "_slidedrag", "slidebeforechange": "_change", "blur": "_change", "keyup": "_change" }); this._on({ "mousedown":"_change" }); this._on( this.element.closest( "form" ), { "reset":"_handleReset" }); this._on( firstHandle, { "vmousedown": "_dragFirstHandle" }); }, _handleReset: function() { var self = this; //we must wait for the stack to unwind before updateing other wise sliders will not have updated yet setTimeout( function() { self._updateHighlight(); },0); }, _dragFirstHandle: function( event ) { //if the first handle is dragged send the event to the first slider $.data( this._inputFirst.get(0), "mobile-slider" ).dragging = true; $.data( this._inputFirst.get(0), "mobile-slider" ).refresh( event ); return false; }, _slidedrag: function( event ) { var first = $( event.target ).is( this._inputFirst ), otherSlider = ( first ) ? this._inputLast : this._inputFirst; this._sliderTarget = false; //if the drag was initiated on an extreme and the other handle is focused send the events to //the closest handle if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) { $.data( otherSlider.get(0), "mobile-slider" ).dragging = true; $.data( otherSlider.get(0), "mobile-slider" ).refresh( event ); return false; } }, _slidestop: function( event ) { var first = $( event.target ).is( this._inputFirst ); this._proxy = false; //this stops dragging of the handle and brings the active track to the front //this makes clicks on the track go the the last handle used this.element.find( "input" ).trigger( "vmouseup" ); this._sliderFirst.css( "z-index", first ? 1 : "" ); }, _slidebeforestart: function( event ) { this._sliderTarget = false; //if the track is the target remember this and the original value if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) { this._sliderTarget = true; this._targetVal = $( event.target ).val(); } }, _setOptions: function( options ) { if ( options.theme !== undefined ) { this._setTheme( options.theme ); } if ( options.trackTheme !== undefined ) { this._setTrackTheme( options.trackTheme ); } if ( options.mini !== undefined ) { this._setMini( options.mini ); } if ( options.highlight !== undefined ) { this._setHighlight( options.highlight ); } this._super( options ); this.refresh(); }, refresh: function() { var $el = this.element, o = this.options; if ( this._inputFirst.is( ":disabled" ) || this._inputLast.is( ":disabled" ) ) { this.options.disabled = true; } $el.find( "input" ).slider({ theme: o.theme, trackTheme: o.trackTheme, disabled: o.disabled, corners: o.corners, mini: o.mini, highlight: o.highlight }).slider( "refresh" ); this._updateHighlight(); }, _change: function( event ) { if ( event.type === "keyup" ) { this._updateHighlight(); return false; } var self = this, min = parseFloat( this._inputFirst.val(), 10 ), max = parseFloat( this._inputLast.val(), 10 ), first = $( event.target ).hasClass( "ui-rangeslider-first" ), thisSlider = first ? this._inputFirst : this._inputLast, otherSlider = first ? this._inputLast : this._inputFirst; if ( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ) { thisSlider.blur(); } else if ( event.type === "mousedown" ) { return; } if ( min > max && !this._sliderTarget ) { //this prevents min from being greater then max thisSlider.val( first ? max: min ).slider( "refresh" ); this._trigger( "normalize" ); } else if ( min > max ) { //this makes it so clicks on the target on either extreme go to the closest handle thisSlider.val( this._targetVal ).slider( "refresh" ); //You must wait for the stack to unwind so first slider is updated before updating second setTimeout( function() { otherSlider.val( first ? min: max ).slider( "refresh" ); $.data( otherSlider.get(0), "mobile-slider" ).handle.focus(); self._sliderFirst.css( "z-index", first ? "" : 1 ); self._trigger( "normalize" ); }, 0 ); this._proxy = ( first ) ? "first" : "last"; } //fixes issue where when both _sliders are at min they cannot be adjusted if ( min === max ) { $.data( thisSlider.get(0), "mobile-slider" ).handle.css( "z-index", 1 ); $.data( otherSlider.get(0), "mobile-slider" ).handle.css( "z-index", 0 ); } else { $.data( otherSlider.get(0), "mobile-slider" ).handle.css( "z-index", "" ); $.data( thisSlider.get(0), "mobile-slider" ).handle.css( "z-index", "" ); } this._updateHighlight(); if ( min >= max ) { return false; } }, _updateHighlight: function() { var min = parseInt( $.data( this._inputFirst.get(0), "mobile-slider" ).handle.get(0).style.left, 10 ), max = parseInt( $.data( this._inputLast.get(0), "mobile-slider" ).handle.get(0).style.left, 10 ), width = (max - min); this.element.find( ".ui-slider-bg" ).css({ "margin-left": min + "%", "width": width + "%" }); }, _setTheme: function( value ) { this._inputFirst.slider( "option", "theme", value ); this._inputLast.slider( "option", "theme", value ); }, _setTrackTheme: function( value ) { this._inputFirst.slider( "option", "trackTheme", value ); this._inputLast.slider( "option", "trackTheme", value ); }, _setMini: function( value ) { this._inputFirst.slider( "option", "mini", value ); this._inputLast.slider( "option", "mini", value ); this.element.toggleClass( "ui-mini", !!value ); }, _setHighlight: function( value ) { this._inputFirst.slider( "option", "highlight", value ); this._inputLast.slider( "option", "highlight", value ); }, _destroy: function() { this._label.prependTo( this.element ); this.element.removeClass( "ui-rangeslider ui-mini" ); this._inputFirst.after( this._sliderFirst ); this._inputLast.after( this._sliderLast ); this._sliders.remove(); this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.textinput, { options: { clearBtn: false, clearBtnText: "Clear text" }, _create: function() { this._super(); if ( !!this.options.clearBtn || this.isSearch ) { this._addClearBtn(); } }, clearButton: function() { return $( "<a href='#' class='ui-input-clear ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all" + "' title='" + this.options.clearBtnText + "'>" + this.options.clearBtnText + "</a>" ); }, _clearBtnClick: function( event ) { this.element.val( "" ) .focus() .trigger( "change" ); this._clearBtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }, _addClearBtn: function() { if ( !this.options.enhanced ) { this._enhanceClear(); } $.extend( this, { _clearBtn: this.widget().find("a.ui-input-clear") }); this._bindClearEvents(); this._toggleClear(); }, _enhanceClear: function() { this.clearButton().appendTo( this.widget() ); this.widget().addClass( "ui-input-has-clear" ); }, _bindClearEvents: function() { this._on( this._clearBtn, { "click": "_clearBtnClick" }); this._on({ "keyup": "_toggleClear", "change": "_toggleClear", "input": "_toggleClear", "focus": "_toggleClear", "blur": "_toggleClear", "cut": "_toggleClear", "paste": "_toggleClear" }); }, _unbindClear: function() { this._off( this._clearBtn, "click"); this._off( this.element, "keyup change input focus blur cut paste" ); }, _setOptions: function( options ) { this._super( options ); if ( options.clearBtn !== undefined && !this.element.is( "textarea, :jqmData(type='range')" ) ) { if ( options.clearBtn ) { this._addClearBtn(); } else { this._destroyClear(); } } if ( options.clearBtnText !== undefined && this._clearBtn !== undefined ) { this._clearBtn.text( options.clearBtnText ) .attr("title", options.clearBtnText); } }, _toggleClear: function() { this._delay( "_toggleClearClass", 0 ); }, _toggleClearClass: function() { this._clearBtn.toggleClass( "ui-input-clear-hidden", !this.element.val() ); }, _destroyClear: function() { this.widget().removeClass( "ui-input-has-clear" ); this._unbindClear(); this._clearBtn.remove(); }, _destroy: function() { this._super(); this._destroyClear(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.textinput, { options: { autogrow:true, keyupTimeoutBuffer: 100 }, _create: function() { this._super(); if ( this.options.autogrow && this.isTextarea ) { this._autogrow(); } }, _autogrow: function() { this.element.addClass( "ui-textinput-autogrow" ); this._on({ "keyup": "_timeout", "change": "_timeout", "input": "_timeout", "paste": "_timeout", }); // Attach to the various you-have-become-visible notifications that the // various framework elements emit. // TODO: Remove all but the updatelayout handler once #6426 is fixed. this._on( true, this.document, { // TODO: Move to non-deprecated event "pageshow": "_handleShow", "popupbeforeposition": "_handleShow", "updatelayout": "_handleShow", "panelopen": "_handleShow" }); }, // Synchronously fix the widget height if this widget's parents are such // that they show/hide content at runtime. We still need to check whether // the widget is actually visible in case it is contained inside multiple // such containers. For example: panel contains collapsible contains // autogrow textinput. The panel may emit "panelopen" indicating that its // content has become visible, but the collapsible is still collapsed, so // the autogrow textarea is still not visible. _handleShow: function( event ) { if ( $.contains( event.target, this.element[ 0 ] ) && this.element.is( ":visible" ) ) { if ( event.type !== "popupbeforeposition" ) { this.element .addClass( "ui-textinput-autogrow-resize" ) .animationComplete( $.proxy( function() { this.element.removeClass( "ui-textinput-autogrow-resize" ); }, this ), "transition" ); } this._timeout(); } }, _unbindAutogrow: function() { this.element.removeClass( "ui-textinput-autogrow" ); this._off( this.element, "keyup change input paste" ); this._off( this.document, "pageshow popupbeforeposition updatelayout panelopen" ); }, keyupTimeout: null, _prepareHeightUpdate: function( delay ) { if ( this.keyupTimeout ) { clearTimeout( this.keyupTimeout ); } if ( delay === undefined ) { this._updateHeight(); } else { this.keyupTimeout = this._delay( "_updateHeight", delay ); } }, _timeout: function() { this._prepareHeightUpdate( this.options.keyupTimeoutBuffer ); }, _updateHeight: function() { var paddingTop, paddingBottom, paddingHeight, scrollHeight, clientHeight, borderTop, borderBottom, borderHeight, height, scrollTop = this.window.scrollTop(); this.keyupTimeout = 0; // IE8 textareas have the onpage property - others do not if ( !( "onpage" in this.element[ 0 ] ) ) { this.element.css({ "height": 0, "min-height": 0, "max-height": 0 }); } scrollHeight = this.element[ 0 ].scrollHeight; clientHeight = this.element[ 0 ].clientHeight; borderTop = parseFloat( this.element.css( "border-top-width" ) ); borderBottom = parseFloat( this.element.css( "border-bottom-width" ) ); borderHeight = borderTop + borderBottom; height = scrollHeight + borderHeight + 15; // Issue 6179: Padding is not included in scrollHeight and // clientHeight by Firefox if no scrollbar is visible. Because // textareas use the border-box box-sizing model, padding should be // included in the new (assigned) height. Because the height is set // to 0, clientHeight == 0 in Firefox. Therefore, we can use this to // check if padding must be added. if ( clientHeight === 0 ) { paddingTop = parseFloat( this.element.css( "padding-top" ) ); paddingBottom = parseFloat( this.element.css( "padding-bottom" ) ); paddingHeight = paddingTop + paddingBottom; height += paddingHeight; } this.element.css({ "height": height, "min-height": "", "max-height": "" }); this.window.scrollTop( scrollTop ); }, refresh: function() { if ( this.options.autogrow && this.isTextarea ) { this._updateHeight(); } }, _setOptions: function( options ) { this._super( options ); if ( options.autogrow !== undefined && this.isTextarea ) { if ( options.autogrow ) { this._autogrow(); } else { this._unbindAutogrow(); } } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.selectmenu", $.extend( { initSelector: "select:not( :jqmData(role='slider')):not( :jqmData(role='flipswitch') )", options: { theme: null, icon: "carat-d", iconpos: "right", inline: false, corners: true, shadow: true, iconshadow: false, /* TODO: Deprecated in 1.4, remove in 1.5. */ overlayTheme: null, dividerTheme: null, hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, mini: false }, _button: function() { return $( "<div/>" ); }, _setDisabled: function( value ) { this.element.attr( "disabled", value ); this.button.attr( "aria-disabled", value ); return this._setOption( "disabled", value ); }, _focusButton : function() { var self = this; setTimeout( function() { self.button.focus(); }, 40); }, _selectOptions: function() { return this.select.find( "option" ); }, // setup items that are generally necessary for select menu extension _preExtension: function() { var inline = this.options.inline || this.element.jqmData( "inline" ), mini = this.options.mini || this.element.jqmData( "mini" ), classes = ""; // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577 /* if ( $el[0].className.length ) { classes = $el[0].className; } */ if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) { classes = " ui-btn-left"; } if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) { classes = " ui-btn-right"; } if ( inline ) { classes += " ui-btn-inline"; } if ( mini ) { classes += " ui-mini"; } this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" ); this.selectId = this.select.attr( "id" ) || ( "select-" + this.uuid ); this.buttonId = this.selectId + "-button"; this.label = $( "label[for='"+ this.selectId +"']" ); this.isMultiple = this.select[ 0 ].multiple; }, _destroy: function() { var wrapper = this.element.parents( ".ui-select" ); if ( wrapper.length > 0 ) { if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) { this.element.addClass( wrapper.hasClass( "ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" ); } this.element.insertAfter( wrapper ); wrapper.remove(); } }, _create: function() { this._preExtension(); this.button = this._button(); var self = this, options = this.options, iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false, button = this.button .insertBefore( this.select ) .attr( "id", this.buttonId ) .addClass( "ui-btn" + ( options.icon ? ( " ui-icon-" + options.icon + " ui-btn-icon-" + iconpos + ( options.iconshadow ? " ui-shadow-icon" : "" ) ) : "" ) + /* TODO: Remove in 1.5. */ ( options.theme ? " ui-btn-" + options.theme : "" ) + ( options.corners ? " ui-corner-all" : "" ) + ( options.shadow ? " ui-shadow" : "" ) ); this.setButtonText(); // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( options.nativeMenu && window.opera && window.opera.version ) { button.addClass( "ui-select-nativeonly" ); } // Add counter for multi selects if ( this.isMultiple ) { this.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-body-inherit" ) .hide() .appendTo( button.addClass( "ui-li-has-count" ) ); } // Disable if specified if ( options.disabled || this.element.attr( "disabled" )) { this.disable(); } // Events on native select this.select.change(function() { self.refresh(); if ( !!options.nativeMenu ) { this.blur(); } }); this._handleFormReset(); this._on( this.button, { keydown: "_handleKeydown" }); this.build(); }, build: function() { var self = this; this.select .appendTo( self.button ) .bind( "vmousedown", function() { // Add active class to button self.button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus", function() { self.button.addClass( $.mobile.focusClass ); }) .bind( "blur", function() { self.button.removeClass( $.mobile.focusClass ); }) .bind( "focus vmouseover", function() { self.button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove self.button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { self.button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }); // In many situations, iOS will zoom into the select upon tap, this prevents that from happening self.button.bind( "vmousedown", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.label.bind( "click focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.select.bind( "focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.button.bind( "mouseup", function() { if ( self.options.preventFocusZoom ) { setTimeout(function() { $.mobile.zoom.enable( true ); }, 0 ); } }); self.select.bind( "blur", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }); }, selected: function() { return this._selectOptions().filter( ":selected" ); }, selectedIndices: function() { var self = this; return this.selected().map(function() { return self._selectOptions().index( this ); }).get(); }, setButtonText: function() { var self = this, selected = this.selected(), text = this.placeholder, span = $( document.createElement( "span" ) ); this.button.children( "span" ).not( ".ui-li-count" ).remove().end().end().prepend( (function() { if ( selected.length ) { text = selected.map(function() { return $( this ).text(); }).get().join( ", " ); } else { text = self.placeholder; } if ( text ) { span.text( text ); } else { // Set the contents to &nbsp; which we write as &#160; to be XHTML compliant - see gh-6699 span.html( "&#160;" ); } // TODO possibly aggregate multiple select option classes return span .addClass( self.select.attr( "class" ) ) .addClass( selected.attr( "class" ) ) .removeClass( "ui-screen-hidden" ); })()); }, setButtonCount: function() { var selected = this.selected(); // multiple count inside button if ( this.isMultiple ) { this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } }, _handleKeydown: function( /* event */ ) { this._delay( "_refreshButton" ); }, _reset: function() { this.refresh(); }, _refreshButton: function() { this.setButtonText(); this.setButtonCount(); }, refresh: function() { this._refreshButton(); }, // open and close preserved in native selects // to simplify users code when looping over selects open: $.noop, close: $.noop, disable: function() { this._setDisabled( true ); this.button.addClass( "ui-state-disabled" ); }, enable: function() { this._setDisabled( false ); this.button.removeClass( "ui-state-disabled" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.mobile.links = function( target ) { //links within content areas, tests included with page $( target ) .find( "a" ) .jqmEnhanceable() .filter( ":jqmData(rel='popup')[href][href!='']" ) .each( function() { // Accessibility info for popups var element = this, idref = element.getAttribute( "href" ).substring( 1 ); if ( idref ) { element.setAttribute( "aria-haspopup", true ); element.setAttribute( "aria-owns", idref ); element.setAttribute( "aria-expanded", false ); } }) .end() .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }; })( jQuery ); (function( $, undefined ) { function fitSegmentInsideSegment( windowSize, segmentSize, offset, desired ) { var returnValue = desired; if ( windowSize < segmentSize ) { // Center segment if it's bigger than the window returnValue = offset + ( windowSize - segmentSize ) / 2; } else { // Otherwise center it at the desired coordinate while keeping it completely inside the window returnValue = Math.min( Math.max( offset, desired - segmentSize / 2 ), offset + windowSize - segmentSize ); } return returnValue; } function getWindowCoordinates( theWindow ) { return { x: theWindow.scrollLeft(), y: theWindow.scrollTop(), cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ), cy: ( theWindow[ 0 ].innerHeight || theWindow.height() ) }; } $.widget( "mobile.popup", { options: { wrapperClass: null, theme: null, overlayTheme: null, shadow: true, corners: true, transition: "none", positionTo: "origin", tolerance: null, closeLinkSelector: "a:jqmData(rel='back')", closeLinkEvents: "click.popup", navigateEvents: "navigate.popup", closeEvents: "navigate.popup pagebeforechange.popup", dismissible: true, enhanced: false, // NOTE Windows Phone 7 has a scroll position caching issue that // requires us to disable popup history management by default // https://github.com/jquery/jquery-mobile/issues/4784 // // NOTE this option is modified in _create! history: !$.mobile.browser.oldIE }, _create: function() { var theElement = this.element, myId = theElement.attr( "id" ), currentOptions = this.options; // We need to adjust the history option to be false if there's no AJAX nav. // We can't do it in the option declarations because those are run before // it is determined whether there shall be AJAX nav. currentOptions.history = currentOptions.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled; // Define instance variables $.extend( this, { _scrollTop: 0, _page: theElement.closest( ".ui-page" ), _ui: null, _fallbackTransition: "", _currentTransition: false, _prerequisites: null, _isOpen: false, _tolerance: null, _resizeData: null, _ignoreResizeTo: 0, _orientationchangeInProgress: false }); if ( this._page.length === 0 ) { this._page = $( "body" ); } if ( currentOptions.enhanced ) { this._ui = { container: theElement.parent(), screen: theElement.parent().prev(), placeholder: $( this.document[ 0 ].getElementById( myId + "-placeholder" ) ) }; } else { this._ui = this._enhance( theElement, myId ); this._applyTransition( currentOptions.transition ); } this ._setTolerance( currentOptions.tolerance ) ._ui.focusElement = this._ui.container; // Event handlers this._on( this._ui.screen, { "vclick": "_eatEventAndClose" } ); this._on( this.window, { orientationchange: $.proxy( this, "_handleWindowOrientationchange" ), resize: $.proxy( this, "_handleWindowResize" ), keyup: $.proxy( this, "_handleWindowKeyUp" ) }); this._on( this.document, { "focusin": "_handleDocumentFocusIn" } ); }, _enhance: function( theElement, myId ) { var currentOptions = this.options, wrapperClass = currentOptions.wrapperClass, ui = { screen: $( "<div class='ui-screen-hidden ui-popup-screen " + this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) + "'></div>" ), placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ), container: $( "<div class='ui-popup-container ui-popup-hidden ui-popup-truncate" + ( wrapperClass ? ( " " + wrapperClass ) : "" ) + "'></div>" ) }, fragment = this.document[ 0 ].createDocumentFragment(); fragment.appendChild( ui.screen[ 0 ] ); fragment.appendChild( ui.container[ 0 ] ); if ( myId ) { ui.screen.attr( "id", myId + "-screen" ); ui.container.attr( "id", myId + "-popup" ); ui.placeholder .attr( "id", myId + "-placeholder" ) .html( "<!-- placeholder for " + myId + " -->" ); } // Apply the proto this._page[ 0 ].appendChild( fragment ); // Leave a placeholder where the element used to be ui.placeholder.insertAfter( theElement ); theElement .detach() .addClass( "ui-popup " + this._themeClassFromOption( "ui-body-", currentOptions.theme ) + " " + ( currentOptions.shadow ? "ui-overlay-shadow " : "" ) + ( currentOptions.corners ? "ui-corner-all " : "" ) ) .appendTo( ui.container ); return ui; }, _eatEventAndClose: function( theEvent ) { theEvent.preventDefault(); theEvent.stopImmediatePropagation(); if ( this.options.dismissible ) { this.close(); } return false; }, // Make sure the screen covers the entire document - CSS is sometimes not // enough to accomplish this. _resizeScreen: function() { var screen = this._ui.screen, popupHeight = this._ui.container.outerHeight( true ), screenHeight = screen.removeAttr( "style" ).height(), // Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where // the browser hangs if the screen covers the entire document :/ documentHeight = this.document.height() - 1; if ( screenHeight < documentHeight ) { screen.height( documentHeight ); } else if ( popupHeight > screenHeight ) { screen.height( popupHeight ); } }, _handleWindowKeyUp: function( theEvent ) { if ( this._isOpen && theEvent.keyCode === $.mobile.keyCode.ESCAPE ) { return this._eatEventAndClose( theEvent ); } }, _expectResizeEvent: function() { var windowCoordinates = getWindowCoordinates( this.window ); if ( this._resizeData ) { if ( windowCoordinates.x === this._resizeData.windowCoordinates.x && windowCoordinates.y === this._resizeData.windowCoordinates.y && windowCoordinates.cx === this._resizeData.windowCoordinates.cx && windowCoordinates.cy === this._resizeData.windowCoordinates.cy ) { // timeout not refreshed return false; } else { // clear existing timeout - it will be refreshed below clearTimeout( this._resizeData.timeoutId ); } } this._resizeData = { timeoutId: this._delay( "_resizeTimeout", 200 ), windowCoordinates: windowCoordinates }; return true; }, _resizeTimeout: function() { if ( this._isOpen ) { if ( !this._expectResizeEvent() ) { if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-open the popup while leaving the screen intact this._ui.container.removeClass( "ui-popup-hidden ui-popup-truncate" ); this.reposition( { positionTo: "window" } ); this._ignoreResizeEvents(); } this._resizeScreen(); this._resizeData = null; this._orientationchangeInProgress = false; } } else { this._resizeData = null; this._orientationchangeInProgress = false; } }, _stopIgnoringResizeEvents: function() { this._ignoreResizeTo = 0; }, _ignoreResizeEvents: function() { if ( this._ignoreResizeTo ) { clearTimeout( this._ignoreResizeTo ); } this._ignoreResizeTo = this._delay( "_stopIgnoringResizeEvents", 1000 ); }, _handleWindowResize: function(/* theEvent */) { if ( this._isOpen && this._ignoreResizeTo === 0 ) { if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) && !this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-close the popup while leaving the screen intact this._ui.container .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); } } }, _handleWindowOrientationchange: function(/* theEvent */) { if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) { this._expectResizeEvent(); this._orientationchangeInProgress = true; } }, // When the popup is open, attempting to focus on an element that is not a // child of the popup will redirect focus to the popup _handleDocumentFocusIn: function( theEvent ) { var target, targetElement = theEvent.target, ui = this._ui; if ( !this._isOpen ) { return; } if ( targetElement !== ui.container[ 0 ] ) { target = $( targetElement ); if ( 0 === target.parents().filter( ui.container[ 0 ] ).length ) { $( this.document[ 0 ].activeElement ).one( "focus", function(/* theEvent */) { target.blur(); }); ui.focusElement.focus(); theEvent.preventDefault(); theEvent.stopImmediatePropagation(); return false; } else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) { ui.focusElement = target; } } this._ignoreResizeEvents(); }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : ( prefix + value ) ) : ( prefix + "inherit" ) ); }, _applyTransition: function( value ) { if ( value ) { this._ui.container.removeClass( this._fallbackTransition ); if ( value !== "none" ) { this._fallbackTransition = $.mobile._maybeDegradeTransition( value ); if ( this._fallbackTransition === "none" ) { this._fallbackTransition = ""; } this._ui.container.addClass( this._fallbackTransition ); } } return this; }, _setOptions: function( newOptions ) { var currentOptions = this.options, theElement = this.element, screen = this._ui.screen; if ( newOptions.wrapperClass !== undefined ) { this._ui.container .removeClass( currentOptions.wrapperClass ) .addClass( newOptions.wrapperClass ); } if ( newOptions.theme !== undefined ) { theElement .removeClass( this._themeClassFromOption( "ui-body-", currentOptions.theme ) ) .addClass( this._themeClassFromOption( "ui-body-", newOptions.theme ) ); } if ( newOptions.overlayTheme !== undefined ) { screen .removeClass( this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) ) .addClass( this._themeClassFromOption( "ui-overlay-", newOptions.overlayTheme ) ); if ( this._isOpen ) { screen.addClass( "in" ); } } if ( newOptions.shadow !== undefined ) { theElement.toggleClass( "ui-overlay-shadow", newOptions.shadow ); } if ( newOptions.corners !== undefined ) { theElement.toggleClass( "ui-corner-all", newOptions.corners ); } if ( newOptions.transition !== undefined ) { if ( !this._currentTransition ) { this._applyTransition( newOptions.transition ); } } if ( newOptions.tolerance !== undefined ) { this._setTolerance( newOptions.tolerance ); } if ( newOptions.disabled !== undefined ) { if ( newOptions.disabled ) { this.close(); } } return this._super( newOptions ); }, _setTolerance: function( value ) { var tol = { t: 30, r: 15, b: 30, l: 15 }, ar; if ( value !== undefined ) { ar = String( value ).split( "," ); $.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } ); switch( ar.length ) { // All values are to be the same case 1: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.r = tol.b = tol.l = ar[ 0 ]; } break; // The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance case 2: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.b = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.l = tol.r = ar[ 1 ]; } break; // The array contains values in the order top, right, bottom, left case 4: if ( !isNaN( ar[ 0 ] ) ) { tol.t = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.r = ar[ 1 ]; } if ( !isNaN( ar[ 2 ] ) ) { tol.b = ar[ 2 ]; } if ( !isNaN( ar[ 3 ] ) ) { tol.l = ar[ 3 ]; } break; default: break; } } this._tolerance = tol; return this; }, _clampPopupWidth: function( infoOnly ) { var menuSize, windowCoordinates = getWindowCoordinates( this.window ), // rectangle within which the popup must fit rectangle = { x: this._tolerance.l, y: windowCoordinates.y + this._tolerance.t, cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r, cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b }; if ( !infoOnly ) { // Clamp the width of the menu before grabbing its size this._ui.container.css( "max-width", rectangle.cx ); } menuSize = { cx: this._ui.container.outerWidth( true ), cy: this._ui.container.outerHeight( true ) }; return { rc: rectangle, menuSize: menuSize }; }, _calculateFinalLocation: function( desired, clampInfo ) { var returnValue, rectangle = clampInfo.rc, menuSize = clampInfo.menuSize; // Center the menu over the desired coordinates, while not going outside // the window tolerances. This will center wrt. the window if the popup is // too large. returnValue = { left: fitSegmentInsideSegment( rectangle.cx, menuSize.cx, rectangle.x, desired.x ), top: fitSegmentInsideSegment( rectangle.cy, menuSize.cy, rectangle.y, desired.y ) }; // Make sure the top of the menu is visible returnValue.top = Math.max( 0, returnValue.top ); // If the height of the menu is smaller than the height of the document // align the bottom with the bottom of the document returnValue.top -= Math.min( returnValue.top, Math.max( 0, returnValue.top + menuSize.cy - this.document.height() ) ); return returnValue; }, // Try and center the overlay over the given coordinates _placementCoords: function( desired ) { return this._calculateFinalLocation( desired, this._clampPopupWidth() ); }, _createPrerequisites: function( screenPrerequisite, containerPrerequisite, whenDone ) { var prerequisites, self = this; // It is important to maintain both the local variable prerequisites and // self._prerequisites. The local variable remains in the closure of the // functions which call the callbacks passed in. The comparison between the // local variable and self._prerequisites is necessary, because once a // function has been passed to .animationComplete() it will be called next // time an animation completes, even if that's not the animation whose end // the function was supposed to catch (for example, if an abort happens // during the opening animation, the .animationComplete handler is not // called for that animation anymore, but the handler remains attached, so // it is called the next time the popup is opened - making it stale. // Comparing the local variable prerequisites to the widget-level variable // self._prerequisites ensures that callbacks triggered by a stale // .animationComplete will be ignored. prerequisites = { screen: $.Deferred(), container: $.Deferred() }; prerequisites.screen.then( function() { if ( prerequisites === self._prerequisites ) { screenPrerequisite(); } }); prerequisites.container.then( function() { if ( prerequisites === self._prerequisites ) { containerPrerequisite(); } }); $.when( prerequisites.screen, prerequisites.container ).done( function() { if ( prerequisites === self._prerequisites ) { self._prerequisites = null; whenDone(); } }); self._prerequisites = prerequisites; }, _animate: function( args ) { // NOTE before removing the default animation of the screen // this had an animate callback that would resolve the deferred // now the deferred is resolved immediately // TODO remove the dependency on the screen deferred this._ui.screen .removeClass( args.classToRemove ) .addClass( args.screenClassToAdd ); args.prerequisites.screen.resolve(); if ( args.transition && args.transition !== "none" ) { if ( args.applyTransition ) { this._applyTransition( args.transition ); } if ( this._fallbackTransition ) { this._ui.container .addClass( args.containerClassToAdd ) .removeClass( args.classToRemove ) .animationComplete( $.proxy( args.prerequisites.container, "resolve" ) ); return; } } this._ui.container.removeClass( args.classToRemove ); args.prerequisites.container.resolve(); }, // The desired coordinates passed in will be returned untouched if no reference element can be identified via // desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid // x and y coordinates by specifying the center middle of the window if the coordinates are absent. // options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector _desiredCoords: function( openOptions ) { var offset, dst = null, windowCoordinates = getWindowCoordinates( this.window ), x = openOptions.x, y = openOptions.y, pTo = openOptions.positionTo; // Establish which element will serve as the reference if ( pTo && pTo !== "origin" ) { if ( pTo === "window" ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; y = windowCoordinates.cy / 2 + windowCoordinates.y; } else { try { dst = $( pTo ); } catch( err ) { dst = null; } if ( dst ) { dst.filter( ":visible" ); if ( dst.length === 0 ) { dst = null; } } } } // If an element was found, center over it if ( dst ) { offset = dst.offset(); x = offset.left + dst.outerWidth() / 2; y = offset.top + dst.outerHeight() / 2; } // Make sure x and y are valid numbers - center over the window if ( $.type( x ) !== "number" || isNaN( x ) ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; } if ( $.type( y ) !== "number" || isNaN( y ) ) { y = windowCoordinates.cy / 2 + windowCoordinates.y; } return { x: x, y: y }; }, _reposition: function( openOptions ) { // We only care about position-related parameters for repositioning openOptions = { x: openOptions.x, y: openOptions.y, positionTo: openOptions.positionTo }; this._trigger( "beforeposition", undefined, openOptions ); this._ui.container.offset( this._placementCoords( this._desiredCoords( openOptions ) ) ); }, reposition: function( openOptions ) { if ( this._isOpen ) { this._reposition( openOptions ); } }, _openPrerequisitesComplete: function() { var id = this.element.attr( "id" ); this._ui.container.addClass( "ui-popup-active" ); this._isOpen = true; this._resizeScreen(); this._ui.container.attr( "tabindex", "0" ).focus(); this._ignoreResizeEvents(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", true ); } this._trigger( "afteropen" ); }, _open: function( options ) { var openOptions = $.extend( {}, this.options, options ), // TODO move blacklist to private method androidBlacklist = ( function() { var ua = navigator.userAgent, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ), andversion = !!androidmatch && androidmatch[ 1 ], chromematch = ua.indexOf( "Chrome" ) > -1; // Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome. if ( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) { return true; } return false; }()); // Count down to triggering "popupafteropen" - we have two prerequisites: // 1. The popup window animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.noop, $.noop, $.proxy( this, "_openPrerequisitesComplete" ) ); this._currentTransition = openOptions.transition; this._applyTransition( openOptions.transition ); this._ui.screen.removeClass( "ui-screen-hidden" ); this._ui.container.removeClass( "ui-popup-truncate" ); // Give applications a chance to modify the contents of the container before it appears this._reposition( openOptions ); this._ui.container.removeClass( "ui-popup-hidden" ); if ( this.options.overlayTheme && androidBlacklist ) { /* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3 This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ): https://github.com/jquery/jquery-mobile/issues/4816 https://github.com/jquery/jquery-mobile/issues/4844 https://github.com/jquery/jquery-mobile/issues/4874 */ // TODO sort out why this._page isn't working this.element.closest( ".ui-page" ).addClass( "ui-popup-open" ); } this._animate({ additionalCondition: true, transition: openOptions.transition, classToRemove: "", screenClassToAdd: "in", containerClassToAdd: "in", applyTransition: false, prerequisites: this._prerequisites }); }, _closePrerequisiteScreen: function() { this._ui.screen .removeClass( "out" ) .addClass( "ui-screen-hidden" ); }, _closePrerequisiteContainer: function() { this._ui.container .removeClass( "reverse out" ) .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); }, _closePrerequisitesDone: function() { var container = this._ui.container, id = this.element.attr( "id" ); container.removeAttr( "tabindex" ); // remove the global mutex for popups $.mobile.popup.active = undefined; // Blur elements inside the container, including the container $( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", false ); } // alert users that the popup is closed this._trigger( "afterclose" ); }, _close: function( immediate ) { this._ui.container.removeClass( "ui-popup-active" ); this._page.removeClass( "ui-popup-open" ); this._isOpen = false; // Count down to triggering "popupafterclose" - we have two prerequisites: // 1. The popup window reverse animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.proxy( this, "_closePrerequisiteScreen" ), $.proxy( this, "_closePrerequisiteContainer" ), $.proxy( this, "_closePrerequisitesDone" ) ); this._animate( { additionalCondition: this._ui.screen.hasClass( "in" ), transition: ( immediate ? "none" : ( this._currentTransition ) ), classToRemove: "in", screenClassToAdd: "out", containerClassToAdd: "reverse out", applyTransition: true, prerequisites: this._prerequisites }); }, _unenhance: function() { if ( this.options.enhanced ) { return; } // Put the element back to where the placeholder was and remove the "ui-popup" class this._setOptions( { theme: $.mobile.popup.prototype.options.theme } ); this.element // Cannot directly insertAfter() - we need to detach() first, because // insertAfter() will do nothing if the payload div was not attached // to the DOM at the time the widget was created, and so the payload // will remain inside the container even after we call insertAfter(). // If that happens and we remove the container a few lines below, we // will cause an infinite recursion - #5244 .detach() .insertAfter( this._ui.placeholder ) .removeClass( "ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit" ); this._ui.screen.remove(); this._ui.container.remove(); this._ui.placeholder.remove(); }, _destroy: function() { if ( $.mobile.popup.active === this ) { this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) ); this.close(); } else { this._unenhance(); } return this; }, _closePopup: function( theEvent, data ) { var parsedDst, toUrl, currentOptions = this.options, immediate = false; if ( ( theEvent && theEvent.isDefaultPrevented() ) || $.mobile.popup.active !== this ) { return; } // restore location on screen window.scrollTo( 0, this._scrollTop ); if ( theEvent && theEvent.type === "pagebeforechange" && data ) { // Determine whether we need to rapid-close the popup, or whether we can // take the time to run the closing transition if ( typeof data.toPage === "string" ) { parsedDst = data.toPage; } else { parsedDst = data.toPage.jqmData( "url" ); } parsedDst = $.mobile.path.parseUrl( parsedDst ); toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash; if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) { // Going to a different page - close immediately immediate = true; } else { theEvent.preventDefault(); } } // remove nav bindings this.window.off( currentOptions.closeEvents ); // unbind click handlers added when history is disabled this.element.undelegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents ); this._close( immediate ); }, // any navigation event after a popup is opened should close the popup // NOTE the pagebeforechange is bound to catch navigation events that don't // alter the url (eg, dialogs from popups) _bindContainerClose: function() { this.window .on( this.options.closeEvents, $.proxy( this, "_closePopup" ) ); }, widget: function() { return this._ui.container; }, // TODO no clear deliniation of what should be here and // what should be in _open. Seems to be "visual" vs "history" for now open: function( options ) { var url, hashkey, activePage, currentIsDialog, hasHash, urlHistory, self = this, currentOptions = this.options; // make sure open is idempotent if ( $.mobile.popup.active || currentOptions.disabled ) { return this; } // set the global popup mutex $.mobile.popup.active = this; this._scrollTop = this.window.scrollTop(); // if history alteration is disabled close on navigate events // and leave the url as is if ( !( currentOptions.history ) ) { self._open( options ); self._bindContainerClose(); // When histoy is disabled we have to grab the data-rel // back link clicks so we can close the popup instead of // relying on history to do it for us self.element .delegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents, function( theEvent ) { self.close(); theEvent.preventDefault(); }); return this; } // cache some values for min/readability urlHistory = $.mobile.navigate.history; hashkey = $.mobile.dialogHashKey; activePage = $.mobile.activePage; currentIsDialog = ( activePage ? activePage.hasClass( "ui-dialog" ) : false ); this._myUrl = url = urlHistory.getActive().url; hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 ); if ( hasHash ) { self._open( options ); self._bindContainerClose(); return this; } // if the current url has no dialog hash key proceed as normal // otherwise, if the page is a dialog simply tack on the hash key if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ) { url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey); } else { url = $.mobile.path.parseLocation().hash + hashkey; } // Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) { url += hashkey; } // swallow the the initial navigation event, and bind for the next this.window.one( "beforenavigate", function( theEvent ) { theEvent.preventDefault(); self._open( options ); self._bindContainerClose(); }); this.urlAltered = true; $.mobile.navigate( url, { role: "dialog" } ); return this; }, close: function() { // make sure close is idempotent if ( $.mobile.popup.active !== this ) { return this; } this._scrollTop = this.window.scrollTop(); if ( this.options.history && this.urlAltered ) { $.mobile.back(); this.urlAltered = false; } else { // simulate the nav bindings having fired this._closePopup(); } return this; } }); // TODO this can be moved inside the widget $.mobile.popup.handleLink = function( $link ) { var offset, path = $.mobile.path, // NOTE make sure to get only the hash from the href because ie7 (wp7) // returns the absolute href in this case ruining the element selection popup = $( path.hashToSelector( path.parseUrl( $link.attr( "href" ) ).hash ) ).first(); if ( popup.length > 0 && popup.data( "mobile-popup" ) ) { offset = $link.offset(); popup.popup( "open", { x: offset.left + $link.outerWidth() / 2, y: offset.top + $link.outerHeight() / 2, transition: $link.jqmData( "transition" ), positionTo: $link.jqmData( "position-to" ) }); } //remove after delay setTimeout( function() { $link.removeClass( $.mobile.activeBtnClass ); }, 300 ); }; // TODO move inside _create $.mobile.document.on( "pagebeforechange", function( theEvent, data ) { if ( data.options.role === "popup" ) { $.mobile.popup.handleLink( data.options.link ); theEvent.preventDefault(); } }); })( jQuery ); /* * custom "selectmenu" plugin */ (function( $, undefined ) { var unfocusableItemSelector = ".ui-disabled,.ui-state-disabled,.ui-li-divider,.ui-screen-hidden,:jqmData(role='placeholder')", goToAdjacentItem = function( item, target, direction ) { var adjacent = item[ direction + "All" ]() .not( unfocusableItemSelector ) .first(); // if there's a previous option, focus it if ( adjacent.length ) { target .blur() .attr( "tabindex", "-1" ); adjacent.find( "a" ).first().focus(); } }; $.widget( "mobile.selectmenu", $.mobile.selectmenu, { _create: function() { var o = this.options; // Custom selects cannot exist inside popups, so revert the "nativeMenu" // option to true if a parent is a popup o.nativeMenu = o.nativeMenu || ( this.element.parents( ":jqmData(role='popup'),:mobile-popup" ).length > 0 ); return this._super(); }, _handleSelectFocus: function() { this.element.blur(); this.button.focus(); }, _handleKeydown: function( event ) { this._super( event ); this._handleButtonVclickKeydown( event ); }, _handleButtonVclickKeydown: function( event ) { if ( this.options.disabled || this.isOpen ) { return; } if (event.type === "vclick" || event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE)) { this._decideFormat(); if ( this.menuType === "overlay" ) { this.button.attr( "href", "#" + this.popupId ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" ); } else { this.button.attr( "href", "#" + this.dialogId ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" ); } this.isOpen = true; // Do not prevent default, so the navigation may have a chance to actually open the chosen format } }, _handleListFocus: function( e ) { var params = ( e.type === "focusin" ) ? { tabindex: "0", event: "vmouseover" }: { tabindex: "-1", event: "vmouseout" }; $( e.target ) .attr( "tabindex", params.tabindex ) .trigger( params.event ); }, _handleListKeydown: function( event ) { var target = $( event.target ), li = target.closest( "li" ); // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: goToAdjacentItem( li, target, "prev" ); return false; // down or right arrow keys case 40: goToAdjacentItem( li, target, "next" ); return false; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "click" ); return false; } }, _handleMenuPageHide: function() { // TODO centralize page removal binding / handling in the page plugin. // Suggestion from @jblas to do refcounting // // TODO extremely confusing dependency on the open method where the pagehide.remove // bindings are stripped to prevent the parent page from disappearing. The way // we're keeping pages in the DOM right now sucks // // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select // // doing this here provides for the back button on the custom select dialog this.thisPage.page( "bindRemove" ); }, _handleHeaderCloseClick: function() { if ( this.menuType === "overlay" ) { this.close(); return false; } }, build: function() { var selectId, popupId, dialogId, label, thisPage, isMultiple, menuId, themeAttr, overlayTheme, overlayThemeAttr, dividerThemeAttr, menuPage, listbox, list, header, headerTitle, menuPageContent, menuPageClose, headerClose, self, o = this.options; if ( o.nativeMenu ) { return this._super(); } self = this; selectId = this.selectId; popupId = selectId + "-listbox"; dialogId = selectId + "-dialog"; label = this.label; thisPage = this.element.closest( ".ui-page" ); isMultiple = this.element[ 0 ].multiple; menuId = selectId + "-menu"; themeAttr = o.theme ? ( " data-" + $.mobile.ns + "theme='" + o.theme + "'" ) : ""; overlayTheme = o.overlayTheme || o.theme || null; overlayThemeAttr = overlayTheme ? ( " data-" + $.mobile.ns + "overlay-theme='" + overlayTheme + "'" ) : ""; dividerThemeAttr = ( o.dividerTheme && isMultiple ) ? ( " data-" + $.mobile.ns + "divider-theme='" + o.dividerTheme + "'" ) : ""; menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' class='ui-selectmenu' id='" + dialogId + "'" + themeAttr + overlayThemeAttr + ">" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.getEncodedText() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ); listbox = $( "<div id='" + popupId + "' class='ui-selectmenu'></div>" ).insertAfter( this.select ).popup({ theme: o.overlayTheme }); list = $( "<ul class='ui-selectmenu-list' id='" + menuId + "' role='listbox' aria-labelledby='" + this.buttonId + "'" + themeAttr + dividerThemeAttr + "></ul>" ).appendTo( listbox ); header = $( "<div class='ui-header ui-bar-" + ( o.theme ? o.theme : "inherit" ) + "'></div>" ).prependTo( listbox ); headerTitle = $( "<h1 class='ui-title'></h1>" ).appendTo( header ); if ( this.isMultiple ) { headerClose = $( "<a>", { "role": "button", "text": o.closeText, "href": "#", "class": "ui-btn ui-corner-all ui-btn-left ui-btn-icon-notext ui-icon-delete" }).appendTo( header ); } $.extend( this, { selectId: selectId, menuId: menuId, popupId: popupId, dialogId: dialogId, thisPage: thisPage, menuPage: menuPage, label: label, isMultiple: isMultiple, theme: o.theme, listbox: listbox, list: list, header: header, headerTitle: headerTitle, headerClose: headerClose, menuPageContent: menuPageContent, menuPageClose: menuPageClose, placeholder: "" }); // Create list from select, update state this.refresh(); if ( this._origTabIndex === undefined ) { // Map undefined to false, because this._origTabIndex === undefined // indicates that we have not yet checked whether the select has // originally had a tabindex attribute, whereas false indicates that // we have checked the select for such an attribute, and have found // none present. this._origTabIndex = ( this.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : this.select.attr( "tabindex" ); } this.select.attr( "tabindex", "-1" ); this._on( this.select, { focus : "_handleSelectFocus" } ); // Button events this._on( this.button, { vclick: "_handleButtonVclickKeydown" }); // Events for list items this.list.attr( "role", "listbox" ); this._on( this.list, { focusin : "_handleListFocus", focusout : "_handleListFocus", keydown: "_handleListKeydown" }); this.list .delegate( "li:not(.ui-disabled,.ui-state-disabled,.ui-li-divider)", "click", function( event ) { // index of option tag to be selected var oldIndex = self.select[ 0 ].selectedIndex, newIndex = $.mobile.getAttribute( this, "option-index" ), option = self._selectOptions().eq( newIndex )[ 0 ]; // toggle selected status on the tag for multi selects option.selected = self.isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( self.isMultiple ) { $( this ).find( "a" ) .toggleClass( "ui-checkbox-on", option.selected ) .toggleClass( "ui-checkbox-off", !option.selected ); } // trigger change if value changed if ( self.isMultiple || oldIndex !== newIndex ) { self.select.trigger( "change" ); } // hide custom select for single selects only - otherwise focus clicked item // We need to grab the clicked item the hard way, because the list may have been rebuilt if ( self.isMultiple ) { self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex ) .find( "a" ).first().focus(); } else { self.close(); } event.preventDefault(); }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion this._on( this.menuPage, { pagehide: "_handleMenuPageHide" } ); // Events on the popup this._on( this.listbox, { popupafterclose: "close" } ); // Close button on small overlays if ( this.isMultiple ) { this._on( this.headerClose, { click: "_handleHeaderCloseClick" } ); } return this; }, _isRebuildRequired: function() { var list = this.list.find( "li" ), options = this._selectOptions().not( ".ui-screen-hidden" ); // TODO exceedingly naive method to determine difference // ignores value changes etc in favor of a forcedRebuild // from the user in the refresh method return options.text() !== list.text(); }, selected: function() { return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" ); }, refresh: function( force ) { var self, indices; if ( this.options.nativeMenu ) { return this._super( force ); } self = this; if ( force || this._isRebuildRequired() ) { self._buildList(); } indices = this.selectedIndices(); self.setButtonText(); self.setButtonCount(); self.list.find( "li:not(.ui-li-divider)" ) .find( "a" ).removeClass( $.mobile.activeBtnClass ).end() .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indices ) > -1 ) { var item = $( this ); // Aria selected attr item.attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( self.isMultiple ) { item.find( "a" ).removeClass( "ui-checkbox-off" ).addClass( "ui-checkbox-on" ); } else { if ( item.hasClass( "ui-screen-hidden" ) ) { item.next().find( "a" ).addClass( $.mobile.activeBtnClass ); } else { item.find( "a" ).addClass( $.mobile.activeBtnClass ); } } } }); }, close: function() { if ( this.options.disabled || !this.isOpen ) { return; } var self = this; if ( self.menuType === "page" ) { self.menuPage.dialog( "close" ); self.list.appendTo( self.listbox ); } else { self.listbox.popup( "close" ); } self._focusButton(); // allow the dialog to be closed again self.isOpen = false; }, open: function() { this.button.click(); }, _focusMenuItem: function() { var selector = this.list.find( "a." + $.mobile.activeBtnClass ); if ( selector.length === 0 ) { selector = this.list.find( "li:not(" + unfocusableItemSelector + ") a.ui-btn" ); } selector.first().focus(); }, _decideFormat: function() { var self = this, $window = this.window, selfListParent = self.list.parent(), menuHeight = selfListParent.outerHeight(), scrollTop = $window.scrollTop(), btnOffset = self.button.offset().top, screenHeight = $window.height(); if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { self.menuPage.appendTo( $.mobile.pageContainer ).page(); self.menuPageContent = self.menuPage.find( ".ui-content" ); self.menuPageClose = self.menuPage.find( ".ui-header a" ); // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for WebOS/Opera Mini (set lastscroll using button offset) if ( scrollTop === 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage.one( { pageshow: $.proxy( this, "_focusMenuItem" ), pagehide: $.proxy( this, "close" ) }); self.menuType = "page"; self.menuPageContent.append( self.list ); self.menuPage.find( "div .ui-title" ).text( self.label.text() ); } else { self.menuType = "overlay"; self.listbox.one( { popupafteropen: $.proxy( this, "_focusMenuItem" ) } ); } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, needPlaceholder = true, dataIcon = "false", $options, numOptions, select, dataPrefix = "data-" + $.mobile.ns, dataIndexAttr = dataPrefix + "option-index", dataIconAttr = dataPrefix + "icon", dataRoleAttr = dataPrefix + "role", dataPlaceholderAttr = dataPrefix + "placeholder", fragment = document.createDocumentFragment(), isPlaceholderItem = false, optGroup, i, option, $option, parent, text, anchor, classes, optLabel, divider, item; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); $options = this._selectOptions(); numOptions = $options.length; select = this.select[ 0 ]; for ( i = 0; i < numOptions;i++, isPlaceholderItem = false) { option = $options[i]; $option = $( option ); // Do not create options based on ui-screen-hidden select options if ( $option.hasClass( "ui-screen-hidden" ) ) { continue; } parent = option.parentNode; text = $option.text(); anchor = document.createElement( "a" ); classes = []; anchor.setAttribute( "href", "#" ); anchor.appendChild( document.createTextNode( text ) ); // Are we inside an optgroup? if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) { optLabel = parent.getAttribute( "label" ); if ( optLabel !== optGroup ) { divider = document.createElement( "li" ); divider.setAttribute( dataRoleAttr, "list-divider" ); divider.setAttribute( "role", "option" ); divider.setAttribute( "tabindex", "-1" ); divider.appendChild( document.createTextNode( optLabel ) ); fragment.appendChild( divider ); optGroup = optLabel; } } if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) { needPlaceholder = false; isPlaceholderItem = true; // If we have identified a placeholder, record the fact that it was // us who have added the placeholder to the option and mark it // retroactively in the select as well if ( null === option.getAttribute( dataPlaceholderAttr ) ) { this._removePlaceholderAttr = true; } option.setAttribute( dataPlaceholderAttr, true ); if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-screen-hidden" ); } if ( placeholder !== text ) { placeholder = self.placeholder = text; } } item = document.createElement( "li" ); if ( option.disabled ) { classes.push( "ui-state-disabled" ); item.setAttribute( "aria-disabled", true ); } item.setAttribute( dataIndexAttr, i ); item.setAttribute( dataIconAttr, dataIcon ); if ( isPlaceholderItem ) { item.setAttribute( dataPlaceholderAttr, true ); } item.className = classes.join( " " ); item.setAttribute( "role", "option" ); anchor.setAttribute( "tabindex", "-1" ); if ( this.isMultiple ) { $( anchor ).addClass( "ui-btn ui-checkbox-off ui-btn-icon-right" ); } item.appendChild( anchor ); fragment.appendChild( item ); } self.list[0].appendChild( fragment ); // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.addClass( "ui-screen-hidden" ); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, _button: function() { return this.options.nativeMenu ? this._super() : $( "<a>", { "href": "#", "role": "button", // TODO value is undefined at creation "id": this.buttonId, "aria-haspopup": "true", // TODO value is undefined at creation "aria-owns": this.menuId }); }, _destroy: function() { if ( !this.options.nativeMenu ) { this.close(); // Restore the tabindex attribute to its original value if ( this._origTabIndex !== undefined ) { if ( this._origTabIndex !== false ) { this.select.attr( "tabindex", this._origTabIndex ); } else { this.select.removeAttr( "tabindex" ); } } // Remove the placeholder attribute if we were the ones to add it if ( this._removePlaceholderAttr ) { this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" ); } // Remove the popup this.listbox.remove(); // Remove the dialog this.menuPage.remove(); } // Chain up this._super(); } }); })( jQuery ); // buttonMarkup is deprecated as of 1.4.0 and will be removed in 1.5.0. (function( $, undefined ) { // General policy: Do not access data-* attributes except during enhancement. // In all other cases we determine the state of the button exclusively from its // className. That's why optionsToClasses expects a full complement of options, // and the jQuery plugin completes the set of options from the default values. // Map classes to buttonMarkup boolean options - used in classNameToOptions() var reverseBoolOptionMap = { "ui-shadow" : "shadow", "ui-corner-all" : "corners", "ui-btn-inline" : "inline", "ui-shadow-icon" : "iconshadow", /* TODO: Remove in 1.5 */ "ui-mini" : "mini" }, getAttrFixed = function() { var ret = $.mobile.getAttribute.apply( this, arguments ); return ( ret == null ? undefined : ret ); }, capitalLettersRE = /[A-Z]/g; // optionsToClasses: // @options: A complete set of options to convert to class names. // @existingClasses: extra classes to add to the result // // Converts @options to buttonMarkup classes and returns the result as an array // that can be converted to an element's className with .join( " " ). All // possible options must be set inside @options. Use $.fn.buttonMarkup.defaults // to get a complete set and use $.extend to override your choice of options // from that set. function optionsToClasses( options, existingClasses ) { var classes = existingClasses ? existingClasses : []; // Add classes to the array - first ui-btn classes.push( "ui-btn" ); // If there is a theme if ( options.theme ) { classes.push( "ui-btn-" + options.theme ); } // If there's an icon, add the icon-related classes if ( options.icon ) { classes = classes.concat([ "ui-icon-" + options.icon, "ui-btn-icon-" + options.iconpos ]); if ( options.iconshadow ) { classes.push( "ui-shadow-icon" ); /* TODO: Remove in 1.5 */ } } // Add the appropriate class for each boolean option if ( options.inline ) { classes.push( "ui-btn-inline" ); } if ( options.shadow ) { classes.push( "ui-shadow" ); } if ( options.corners ) { classes.push( "ui-corner-all" ); } if ( options.mini ) { classes.push( "ui-mini" ); } // Create a string from the array and return it return classes; } // classNameToOptions: // @classes: A string containing a .className-style space-separated class list // // Loops over @classes and calculates an options object based on the // buttonMarkup-related classes it finds. It records unrecognized classes in an // array. // // Returns: An object containing the following items: // // "options": buttonMarkup options found to be present because of the // presence/absence of corresponding classes // // "unknownClasses": a string containing all the non-buttonMarkup-related // classes found in @classes // // "alreadyEnhanced": A boolean indicating whether the ui-btn class was among // those found to be present function classNameToOptions( classes ) { var idx, map, unknownClass, alreadyEnhanced = false, noIcon = true, o = { icon: "", inline: false, shadow: false, corners: false, iconshadow: false, mini: false }, unknownClasses = []; classes = classes.split( " " ); // Loop over the classes for ( idx = 0 ; idx < classes.length ; idx++ ) { // Assume it's an unrecognized class unknownClass = true; // Recognize boolean options from the presence of classes map = reverseBoolOptionMap[ classes[ idx ] ]; if ( map !== undefined ) { unknownClass = false; o[ map ] = true; // Recognize the presence of an icon and establish the icon position } else if ( classes[ idx ].indexOf( "ui-btn-icon-" ) === 0 ) { unknownClass = false; noIcon = false; o.iconpos = classes[ idx ].substring( 12 ); // Establish which icon is present } else if ( classes[ idx ].indexOf( "ui-icon-" ) === 0 ) { unknownClass = false; o.icon = classes[ idx ].substring( 8 ); // Establish the theme - this recognizes one-letter theme swatch names } else if ( classes[ idx ].indexOf( "ui-btn-" ) === 0 && classes[ idx ].length === 8 ) { unknownClass = false; o.theme = classes[ idx ].substring( 7 ); // Recognize that this element has already been buttonMarkup-enhanced } else if ( classes[ idx ] === "ui-btn" ) { unknownClass = false; alreadyEnhanced = true; } // If this class has not been recognized, add it to the list if ( unknownClass ) { unknownClasses.push( classes[ idx ] ); } } // If a "ui-btn-icon-*" icon position class is absent there cannot be an icon if ( noIcon ) { o.icon = ""; } return { options: o, unknownClasses: unknownClasses, alreadyEnhanced: alreadyEnhanced }; } function camelCase2Hyphenated( c ) { return "-" + c.toLowerCase(); } // $.fn.buttonMarkup: // DOM: gets/sets .className // // @options: options to apply to the elements in the jQuery object // @overwriteClasses: boolean indicating whether to honour existing classes // // Calculates the classes to apply to the elements in the jQuery object based on // the options passed in. If @overwriteClasses is true, it sets the className // property of each element in the jQuery object to the buttonMarkup classes // it calculates based on the options passed in. // // If you wish to preserve any classes that are already present on the elements // inside the jQuery object, including buttonMarkup-related classes that were // added by a previous call to $.fn.buttonMarkup() or during page enhancement // then you should omit @overwriteClasses or set it to false. $.fn.buttonMarkup = function( options, overwriteClasses ) { var idx, data, el, retrievedOptions, optionKey, defaults = $.fn.buttonMarkup.defaults; for ( idx = 0 ; idx < this.length ; idx++ ) { el = this[ idx ]; data = overwriteClasses ? // Assume this element is not enhanced and ignore its classes { alreadyEnhanced: false, unknownClasses: [] } : // Otherwise analyze existing classes to establish existing options and // classes classNameToOptions( el.className ); retrievedOptions = $.extend( {}, // If the element already has the class ui-btn, then we assume that // it has passed through buttonMarkup before - otherwise, the options // returned by classNameToOptions do not correctly reflect the state of // the element ( data.alreadyEnhanced ? data.options : {} ), // Finally, apply the options passed in options ); // If this is the first call on this element, retrieve remaining options // from the data-attributes if ( !data.alreadyEnhanced ) { for ( optionKey in defaults ) { if ( retrievedOptions[ optionKey ] === undefined ) { retrievedOptions[ optionKey ] = getAttrFixed( el, optionKey.replace( capitalLettersRE, camelCase2Hyphenated ) ); } } } el.className = optionsToClasses( // Merge all the options and apply them as classes $.extend( {}, // The defaults form the basis defaults, // Add the computed options retrievedOptions ), // ... and re-apply any unrecognized classes that were found data.unknownClasses ).join( " " ); if ( el.tagName.toLowerCase() !== "button" ) { el.setAttribute( "role", "button" ); } } return this; }; // buttonMarkup defaults. This must be a complete set, i.e., a value must be // given here for all recognized options $.fn.buttonMarkup.defaults = { icon: "", iconpos: "left", theme: null, inline: false, shadow: true, corners: true, iconshadow: false, /* TODO: Remove in 1.5. Option deprecated in 1.4. */ mini: false }; $.extend( $.fn.buttonMarkup, { initSelector: "a:jqmData(role='button'), .ui-bar > a, .ui-bar > :jqmData(role='controlgroup') > a, button" }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.controlgroup", $.extend( { options: { enhanced: false, theme: null, shadow: false, corners: true, excludeInvisible: true, type: "vertical", mini: false }, _create: function() { var elem = this.element, opts = this.options; // Run buttonmarkup if ( $.fn.buttonMarkup ) { this.element.find( $.fn.buttonMarkup.initSelector ).buttonMarkup(); } // Enhance child widgets $.each( this._childWidgets, $.proxy( function( number, widgetName ) { if ( $.mobile[ widgetName ] ) { this.element.find( $.mobile[ widgetName ].initSelector ).not( $.mobile.page.prototype.keepNativeSelector() )[ widgetName ](); } }, this )); $.extend( this, { _ui: null, _initialRefresh: true }); if ( opts.enhanced ) { this._ui = { groupLegend: elem.children( ".ui-controlgroup-label" ).children(), childWrapper: elem.children( ".ui-controlgroup-controls" ) }; } else { this._ui = this._enhance(); } }, _childWidgets: [ "checkboxradio", "selectmenu", "button" ], _themeClassFromOption: function( value ) { return ( value ? ( value === "none" ? "" : "ui-group-theme-" + value ) : "" ); }, _enhance: function() { var elem = this.element, opts = this.options, ui = { groupLegend: elem.children( "legend" ), childWrapper: elem .addClass( "ui-controlgroup " + "ui-controlgroup-" + ( opts.type === "horizontal" ? "horizontal" : "vertical" ) + " " + this._themeClassFromOption( opts.theme ) + " " + ( opts.corners ? "ui-corner-all " : "" ) + ( opts.mini ? "ui-mini " : "" ) ) .wrapInner( "<div " + "class='ui-controlgroup-controls " + ( opts.shadow === true ? "ui-shadow" : "" ) + "'></div>" ) .children() }; if ( ui.groupLegend.length > 0 ) { $( "<div role='heading' class='ui-controlgroup-label'></div>" ) .append( ui.groupLegend ) .prependTo( elem ); } return ui; }, _init: function() { this.refresh(); }, _setOptions: function( options ) { var callRefresh, returnValue, elem = this.element; // Must have one of horizontal or vertical if ( options.type !== undefined ) { elem .removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" ) .addClass( "ui-controlgroup-" + ( options.type === "horizontal" ? "horizontal" : "vertical" ) ); callRefresh = true; } if ( options.theme !== undefined ) { elem .removeClass( this._themeClassFromOption( this.options.theme ) ) .addClass( this._themeClassFromOption( options.theme ) ); } if ( options.corners !== undefined ) { elem.toggleClass( "ui-corner-all", options.corners ); } if ( options.mini !== undefined ) { elem.toggleClass( "ui-mini", options.mini ); } if ( options.shadow !== undefined ) { this._ui.childWrapper.toggleClass( "ui-shadow", options.shadow ); } if ( options.excludeInvisible !== undefined ) { this.options.excludeInvisible = options.excludeInvisible; callRefresh = true; } returnValue = this._super( options ); if ( callRefresh ) { this.refresh(); } return returnValue; }, container: function() { return this._ui.childWrapper; }, refresh: function() { var $el = this.container(), els = $el.find( ".ui-btn" ).not( ".ui-slider-handle" ), create = this._initialRefresh; if ( $.mobile.checkboxradio ) { $el.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" ); } this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create ); this._initialRefresh = false; }, // Caveat: If the legend is not the first child of the controlgroup at enhance // time, it will be after _destroy(). _destroy: function() { var ui, buttons, opts = this.options; if ( opts.enhanced ) { return this; } ui = this._ui; buttons = this.element .removeClass( "ui-controlgroup " + "ui-controlgroup-horizontal ui-controlgroup-vertical ui-corner-all ui-mini " + this._themeClassFromOption( opts.theme ) ) .find( ".ui-btn" ) .not( ".ui-slider-handle" ); this._removeFirstLastClasses( buttons ); ui.groupLegend.unwrap(); ui.childWrapper.children().unwrap(); } }, $.mobile.behaviors.addFirstLastClasses ) ); })(jQuery); (function( $, undefined ) { $.widget( "mobile.toolbar", { initSelector: ":jqmData(role='footer'), :jqmData(role='header')", options: { theme: null, addBackBtn: false, backBtnTheme: null, backBtnText: "Back" }, _create: function() { var leftbtn, rightbtn, role = this.element.is( ":jqmData(role='header')" ) ? "header" : "footer", page = this.element.closest( ".ui-page" ); if ( page.length === 0 ) { page = false; this._on( this.document, { "pageshow": "refresh" }); } $.extend( this, { role: role, page: page, leftbtn: leftbtn, rightbtn: rightbtn, backBtn: null }); this.element.attr( "role", role === "header" ? "banner" : "contentinfo" ).addClass( "ui-" + role ); this.refresh(); this._setOptions( this.options ); }, _setOptions: function( o ) { if ( o.addBackBtn !== undefined ) { if ( this.options.addBackBtn && this.role === "header" && $( ".ui-page" ).length > 1 && this.page[ 0 ].getAttribute( "data-" + $.mobile.ns + "url" ) !== $.mobile.path.stripHash( location.hash ) && !this.leftbtn ) { this._addBackButton(); } else { this.element.find( ".ui-toolbar-back-btn" ).remove(); } } if ( o.backBtnTheme != null ) { this.element .find( ".ui-toolbar-back-btn" ) .addClass( "ui-btn ui-btn-" + o.backBtnTheme ); } if ( o.backBtnText !== undefined ) { this.element.find( ".ui-toolbar-back-btn .ui-btn-text" ).text( o.backBtnText ); } if ( o.theme !== undefined ) { var currentTheme = this.options.theme ? this.options.theme : "inherit", newTheme = o.theme ? o.theme : "inherit"; this.element.removeClass( "ui-bar-" + currentTheme ).addClass( "ui-bar-" + newTheme ); } this._super( o ); }, refresh: function() { if ( this.role === "header" ) { this._addHeaderButtonClasses(); } if ( !this.page ) { this._setRelative(); if ( this.role === "footer" ) { this.element.appendTo( "body" ); } } this._addHeadingClasses(); this._btnMarkup(); }, //we only want this to run on non fixed toolbars so make it easy to override _setRelative: function() { $( "[data-"+ $.mobile.ns + "role='page']" ).css({ "position": "relative" }); }, // Deprecated in 1.4. As from 1.5 button classes have to be present in the markup. _btnMarkup: function() { this.element .children( "a" ) .filter( ":not([data-" + $.mobile.ns + "role='none'])" ) .attr( "data-" + $.mobile.ns + "role", "button" ); this.element.trigger( "create" ); }, // Deprecated in 1.4. As from 1.5 ui-btn-left/right classes have to be present in the markup. _addHeaderButtonClasses: function() { var $headeranchors = this.element.children( "a, button" ); this.leftbtn = $headeranchors.hasClass( "ui-btn-left" ); this.rightbtn = $headeranchors.hasClass( "ui-btn-right" ); this.leftbtn = this.leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; this.rightbtn = this.rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; }, _addBackButton: function() { var theme, options = this.options; if ( !this.backBtn ) { theme = options.backBtnTheme || options.theme; this.backBtn = $( "<a role='button' href='javascript:void(0);' " + "class='ui-btn ui-corner-all ui-shadow ui-btn-left " + ( theme ? "ui-btn-" + theme + " " : "" ) + "ui-toolbar-back-btn ui-icon-carat-l ui-btn-icon-left' " + "data-" + $.mobile.ns + "rel='back'>" + options.backBtnText + "</a>" ) .prependTo( this.element ); } }, _addHeadingClasses: function() { this.element.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "role": "heading", "aria-level": "1" }); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.toolbar", $.mobile.toolbar, { options: { position:null, visibleOnPageShow: true, disablePageZoom: true, transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown) fullscreen: false, tapToggle: true, tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-flipswitch, .ui-popup, .ui-panel, .ui-panel-dismiss-open", hideDuringFocus: "input, textarea, select", updatePagePadding: true, trackPersistentToolbars: true, // Browser detection! Weeee, here we go... // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately. // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience. // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window // The following function serves to rule out some popular browsers with known fixed-positioning issues // This is a plugin option like any other, so feel free to improve or overwrite it supportBlacklist: function() { return !$.support.fixedPosition; } }, _create: function() { this._super(); if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { this._makeFixed(); } }, _makeFixed: function() { this.element.addClass( "ui-"+ this.role +"-fixed" ); this.updatePagePadding(); this._addTransitionClass(); this._bindPageEvents(); this._bindToggleHandlers(); this._setOptions( this.options ); }, _setOptions: function( o ) { if ( o.position === "fixed" && this.options.position !== "fixed" ) { this._makeFixed(); } if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { var $page = ( !!this.page )? this.page: ( $(".ui-page-active").length > 0 )? $(".ui-page-active"): $(".ui-page").eq(0); if ( o.fullscreen !== undefined) { if ( o.fullscreen ) { this.element.addClass( "ui-"+ this.role +"-fullscreen" ); $page.addClass( "ui-page-" + this.role + "-fullscreen" ); } // If not fullscreen, add class to page to set top or bottom padding else { this.element.removeClass( "ui-"+ this.role +"-fullscreen" ); $page.removeClass( "ui-page-" + this.role + "-fullscreen" ).addClass( "ui-page-" + this.role+ "-fixed" ); } } } this._super(o); }, _addTransitionClass: function() { var tclass = this.options.transition; if ( tclass && tclass !== "none" ) { // use appropriate slide for header or footer if ( tclass === "slide" ) { tclass = this.element.hasClass( "ui-header" ) ? "slidedown" : "slideup"; } this.element.addClass( tclass ); } }, _bindPageEvents: function() { var page = ( !!this.page )? this.element.closest( ".ui-page" ): this.document; //page event bindings // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up // This method is meant to disable zoom while a fixed-positioned toolbar page is visible this._on( page , { "pagebeforeshow": "_handlePageBeforeShow", "webkitAnimationStart":"_handleAnimationStart", "animationstart":"_handleAnimationStart", "updatelayout": "_handleAnimationStart", "pageshow": "_handlePageShow", "pagebeforehide": "_handlePageBeforeHide" }); }, _handlePageBeforeShow: function( ) { var o = this.options; if ( o.disablePageZoom ) { $.mobile.zoom.disable( true ); } if ( !o.visibleOnPageShow ) { this.hide( true ); } }, _handleAnimationStart: function() { if ( this.options.updatePagePadding ) { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); } }, _handlePageShow: function() { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); if ( this.options.updatePagePadding ) { this._on( this.window, { "throttledresize": "updatePagePadding" } ); } }, _handlePageBeforeHide: function( e, ui ) { var o = this.options, thisFooter, thisHeader, nextFooter, nextHeader; if ( o.disablePageZoom ) { $.mobile.zoom.enable( true ); } if ( o.updatePagePadding ) { this._off( this.window, "throttledresize" ); } if ( o.trackPersistentToolbars ) { thisFooter = $( ".ui-footer-fixed:jqmData(id)", this.page ); thisHeader = $( ".ui-header-fixed:jqmData(id)", this.page ); nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(); nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $(); if ( nextFooter.length || nextHeader.length ) { nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer ); ui.nextPage.one( "pageshow", function() { nextHeader.prependTo( this ); nextFooter.appendTo( this ); }); } } }, _visible: true, // This will set the content element's top or bottom padding equal to the toolbar's height updatePagePadding: function( tbPage ) { var $el = this.element, header = ( this.role ==="header" ), pos = parseFloat( $el.css( header ? "top" : "bottom" ) ); // This behavior only applies to "fixed", not "fullscreen" if ( this.options.fullscreen ) { return; } // tbPage argument can be a Page object or an event, if coming from throttled resize. tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this.page || $el.closest( ".ui-page" ); tbPage = ( !!this.page )? this.page: ".ui-page-active"; $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos ); }, _useTransition: function( notransition ) { var $win = this.window, $el = this.element, scroll = $win.scrollTop(), elHeight = $el.height(), pHeight = ( !!this.page )? $el.closest( ".ui-page" ).height():$(".ui-page-active").height(), viewportHeight = $.mobile.getScreenHeight(); return !notransition && ( this.options.transition && this.options.transition !== "none" && ( ( this.role === "header" && !this.options.fullscreen && scroll > elHeight ) || ( this.role === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight ) ) || this.options.fullscreen ); }, show: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element; if ( this._useTransition( notransition ) ) { $el .removeClass( "out " + hideClass ) .addClass( "in" ) .animationComplete(function () { $el.removeClass( "in" ); }); } else { $el.removeClass( hideClass ); } this._visible = true; }, hide: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element, // if it's a slide transition, our new transitions need the reverse class as well to slide outward outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" ); if ( this._useTransition( notransition ) ) { $el .addClass( outclass ) .removeClass( "in" ) .animationComplete(function() { $el.addClass( hideClass ).removeClass( outclass ); }); } else { $el.addClass( hideClass ).removeClass( outclass ); } this._visible = false; }, toggle: function() { this[ this._visible ? "hide" : "show" ](); }, _bindToggleHandlers: function() { var self = this, o = self.options, delayShow, delayHide, isVisible = true, page = ( !!this.page )? this.page: $(".ui-page"); // tap toggle page .bind( "vclick", function( e ) { if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) { self.toggle(); } }) .bind( "focusin focusout", function( e ) { //this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which //positions fixed toolbars in the middle of the screen on pop if the input is near the top or //bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment //and issue #4113 Header and footer change their position after keyboard popup - iOS //and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) { //Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system //controls causes fixed position, tap-toggle false Header to reveal itself // isVisible instead of self._visible because the focusin and focusout events fire twice at the same time // Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed // by a focusout when a native selects opens and the other way around when it closes. if ( e.type === "focusout" && !isVisible ) { isVisible = true; //wait for the stack to unwind and see if we have jumped to another input clearTimeout( delayHide ); delayShow = setTimeout( function() { self.show(); }, 0 ); } else if ( e.type === "focusin" && !!isVisible ) { //if we have jumped to another input clear the time out to cancel the show. clearTimeout( delayShow ); isVisible = false; delayHide = setTimeout( function() { self.hide(); }, 0 ); } } }); }, _setRelative: function() { if( this.options.position !== "fixed" ){ $( "[data-"+ $.mobile.ns + "role='page']" ).css({ "position": "relative" }); } }, _destroy: function() { var $el = this.element, header = $el.hasClass( "ui-header" ); $el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" ); $el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" ); $el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.toolbar", $.mobile.toolbar, { _makeFixed: function() { this._super(); this._workarounds(); }, //check the browser and version and run needed workarounds _workarounds: function() { var ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], os = null, self = this; //set the os we are working in if it dosent match one with workarounds return if ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) { os = "ios"; } else if ( ua.indexOf( "Android" ) > -1 ) { os = "android"; } else { return; } //check os version if it dosent match one with workarounds return if ( os === "ios" ) { //iOS workarounds self._bindScrollWorkaround(); } else if ( os === "android" && wkversion && wkversion < 534 ) { //Android 2.3 run all Android 2.3 workaround self._bindScrollWorkaround(); self._bindListThumbWorkaround(); } else { return; } }, //Utility class for checking header and footer positions relative to viewport _viewportOffset: function() { var $el = this.element, header = $el.hasClass( "ui-header" ), offset = Math.abs( $el.offset().top - this.window.scrollTop() ); if ( !header ) { offset = Math.round( offset - this.window.height() + $el.outerHeight() ) - 60; } return offset; }, //bind events for _triggerRedraw() function _bindScrollWorkaround: function() { var self = this; //bind to scrollstop and check if the toolbars are correctly positioned this._on( this.window, { scrollstop: function() { var viewportOffset = self._viewportOffset(); //check if the header is visible and if its in the right place if ( viewportOffset > 2 && self._visible ) { self._triggerRedraw(); } }}); }, //this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3 //and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used //the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar //setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other //platforms we scope this with the class ui-android-2x-fix _bindListThumbWorkaround: function() { this.element.closest( ".ui-page" ).addClass( "ui-android-2x-fixed" ); }, //this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android //and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers. //this also addresses not on fixed toolbars page in docs //adding 1px of padding to the bottom then removing it causes a "redraw" //which positions the toolbars correctly (they will always be visually correct) _triggerRedraw: function() { var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) ); //trigger page redraw to fix incorrectly positioned fixed elements $( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) + "px" ); //if the padding is reset with out a timeout the reposition will not occure. //this is independant of JQM the browser seems to need the time to react. setTimeout( function() { $( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" ); }, 0 ); }, destroy: function() { this._super(); //Remove the class we added to the page previously in android 2.x this.element.closest( ".ui-page-active" ).removeClass( "ui-android-2x-fix" ); } }); })( jQuery ); ( function( $, undefined ) { var ieHack = ( $.mobile.browser.oldIE && $.mobile.browser.oldIE <= 8 ), uiTemplate = $( "<div class='ui-popup-arrow-guide'></div>" + "<div class='ui-popup-arrow-container" + ( ieHack ? " ie" : "" ) + "'>" + "<div class='ui-popup-arrow'></div>" + "</div>" ); function getArrow() { var clone = uiTemplate.clone(), gd = clone.eq( 0 ), ct = clone.eq( 1 ), ar = ct.children(); return { arEls: ct.add( gd ), gd: gd, ct: ct, ar: ar }; } $.widget( "mobile.popup", $.mobile.popup, { options: { arrow: "" }, _create: function() { var ar, ret = this._super(); if ( this.options.arrow ) { this._ui.arrow = ar = this._addArrow(); } return ret; }, _addArrow: function() { var theme, opts = this.options, ar = getArrow(); theme = this._themeClassFromOption( "ui-body-", opts.theme ); ar.ar.addClass( theme + ( opts.shadow ? " ui-overlay-shadow" : "" ) ); ar.arEls.hide().appendTo( this.element ); return ar; }, _unenhance: function() { var ar = this._ui.arrow; if ( ar ) { ar.arEls.remove(); } return this._super(); }, // Pretend to show an arrow described by @p and @dir and calculate the // distance from the desired point. If a best-distance is passed in, return // the minimum of the one passed in and the one calculated. _tryAnArrow: function( p, dir, desired, s, best ) { var result, r, diff, desiredForArrow = {}, tip = {}; // If the arrow has no wiggle room along the edge of the popup, it cannot // be displayed along the requested edge without it sticking out. if ( s.arFull[ p.dimKey ] > s.guideDims[ p.dimKey ] ) { return best; } desiredForArrow[ p.fst ] = desired[ p.fst ] + ( s.arHalf[ p.oDimKey ] + s.menuHalf[ p.oDimKey ] ) * p.offsetFactor - s.contentBox[ p.fst ] + ( s.clampInfo.menuSize[ p.oDimKey ] - s.contentBox[ p.oDimKey ] ) * p.arrowOffsetFactor; desiredForArrow[ p.snd ] = desired[ p.snd ]; result = s.result || this._calculateFinalLocation( desiredForArrow, s.clampInfo ); r = { x: result.left, y: result.top }; tip[ p.fst ] = r[ p.fst ] + s.contentBox[ p.fst ] + p.tipOffset; tip[ p.snd ] = Math.max( result[ p.prop ] + s.guideOffset[ p.prop ] + s.arHalf[ p.dimKey ], Math.min( result[ p.prop ] + s.guideOffset[ p.prop ] + s.guideDims[ p.dimKey ] - s.arHalf[ p.dimKey ], desired[ p.snd ] ) ); diff = Math.abs( desired.x - tip.x ) + Math.abs( desired.y - tip.y ); if ( !best || diff < best.diff ) { // Convert tip offset to coordinates inside the popup tip[ p.snd ] -= s.arHalf[ p.dimKey ] + result[ p.prop ] + s.contentBox[ p.snd ]; best = { dir: dir, diff: diff, result: result, posProp: p.prop, posVal: tip[ p.snd ] }; } return best; }, _getPlacementState: function( clamp ) { var offset, gdOffset, ar = this._ui.arrow, state = { clampInfo: this._clampPopupWidth( !clamp ), arFull: { cx: ar.ct.width(), cy: ar.ct.height() }, guideDims: { cx: ar.gd.width(), cy: ar.gd.height() }, guideOffset: ar.gd.offset() }; offset = this.element.offset(); ar.gd.css( { left: 0, top: 0, right: 0, bottom: 0 } ); gdOffset = ar.gd.offset(); state.contentBox = { x: gdOffset.left - offset.left, y: gdOffset.top - offset.top, cx: ar.gd.width(), cy: ar.gd.height() }; ar.gd.removeAttr( "style" ); // The arrow box moves between guideOffset and guideOffset + guideDims - arFull state.guideOffset = { left: state.guideOffset.left - offset.left, top: state.guideOffset.top - offset.top }; state.arHalf = { cx: state.arFull.cx / 2, cy: state.arFull.cy / 2 }; state.menuHalf = { cx: state.clampInfo.menuSize.cx / 2, cy: state.clampInfo.menuSize.cy / 2 }; return state; }, _placementCoords: function( desired ) { var state, best, params, elOffset, bgRef, optionValue = this.options.arrow, ar = this._ui.arrow; if ( !ar ) { return this._super( desired ); } ar.arEls.show(); bgRef = {}; state = this._getPlacementState( true ); params = { "l": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: 1, tipOffset: -state.arHalf.cx, arrowOffsetFactor: 0 }, "r": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: -1, tipOffset: state.arHalf.cx + state.contentBox.cx, arrowOffsetFactor: 1 }, "b": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: -1, tipOffset: state.arHalf.cy + state.contentBox.cy, arrowOffsetFactor: 1 }, "t": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: 1, tipOffset: -state.arHalf.cy, arrowOffsetFactor: 0 } }; // Try each side specified in the options to see on which one the arrow // should be placed such that the distance between the tip of the arrow and // the desired coordinates is the shortest. $.each( ( optionValue === true ? "l,t,r,b" : optionValue ).split( "," ), $.proxy( function( key, value ) { best = this._tryAnArrow( params[ value ], value, desired, state, best ); }, this ) ); // Could not place the arrow along any of the edges - behave as if showing // the arrow was turned off. if ( !best ) { ar.arEls.hide(); return this._super( desired ); } // Move the arrow into place ar.ct .removeClass( "ui-popup-arrow-l ui-popup-arrow-t ui-popup-arrow-r ui-popup-arrow-b" ) .addClass( "ui-popup-arrow-" + best.dir ) .removeAttr( "style" ).css( best.posProp, best.posVal ) .show(); // Do not move/size the background div on IE, because we use the arrow div for background as well. if ( !ieHack ) { elOffset = this.element.offset(); bgRef[ params[ best.dir ].fst ] = ar.ct.offset(); bgRef[ params[ best.dir ].snd ] = { left: elOffset.left + state.contentBox.x, top: elOffset.top + state.contentBox.y }; } return best.result; }, _setOptions: function( opts ) { var newTheme, oldTheme = this.options.theme, ar = this._ui.arrow, ret = this._super( opts ); if ( opts.arrow !== undefined ) { if ( !ar && opts.arrow ) { this._ui.arrow = this._addArrow(); // Important to return here so we don't set the same options all over // again below. return; } else if ( ar && !opts.arrow ) { ar.arEls.remove(); this._ui.arrow = null; } } // Reassign with potentially new arrow ar = this._ui.arrow; if ( ar ) { if ( opts.theme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-body-", oldTheme ); newTheme = this._themeClassFromOption( "ui-body-", opts.theme ); ar.ar.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.shadow !== undefined ) { ar.ar.toggleClass( "ui-overlay-shadow", opts.shadow ); } } return ret; }, _destroy: function() { var ar = this._ui.arrow; if ( ar ) { ar.arEls.remove(); } return this._super(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.panel", { options: { classes: { panel: "ui-panel", panelOpen: "ui-panel-open", panelClosed: "ui-panel-closed", panelFixed: "ui-panel-fixed", panelInner: "ui-panel-inner", modal: "ui-panel-dismiss", modalOpen: "ui-panel-dismiss-open", pageContainer: "ui-panel-page-container", pageWrapper: "ui-panel-wrapper", pageFixedToolbar: "ui-panel-fixed-toolbar", pageContentPrefix: "ui-panel-page-content", /* Used for wrapper and fixed toolbars position, display and open classes. */ animate: "ui-panel-animate" }, animate: true, theme: null, position: "left", dismissible: true, display: "reveal", //accepts reveal, push, overlay swipeClose: true, positionFixed: false }, _panelID: null, _closeLink: null, _parentPage: null, _page: null, _modal: null, _panelInner: null, _wrapper: null, _fixedToolbars: null, _create: function() { var el = this.element, parentPage = el.closest( ":jqmData(role='page')" ); // expose some private props to other methods $.extend( this, { _panelID: el.attr( "id" ), _closeLink: el.find( ":jqmData(rel='close')" ), _parentPage: ( parentPage.length > 0 ) ? parentPage : false, _page: this._getPage, _panelInner: this._getPanelInner(), _wrapper: this._getWrapper, _fixedToolbars: this._getFixedToolbars }); this._addPanelClasses(); // if animating, add the class to do so if ( $.support.cssTransform3d && !!this.options.animate ) { this.element.addClass( this.options.classes.animate ); } this._bindUpdateLayout(); this._bindCloseEvents(); this._bindLinkListeners(); this._bindPageEvents(); if ( !!this.options.dismissible ) { this._createModal(); } this._bindSwipeEvents(); }, _getPanelInner: function() { var panelInner = this.element.find( "." + this.options.classes.panelInner ); if ( panelInner.length === 0 ) { panelInner = this.element.children().wrapAll( "<div class='" + this.options.classes.panelInner + "' />" ).parent(); } return panelInner; }, _createModal: function() { var self = this, target = self._parentPage ? self._parentPage.parent() : self.element.parent(); self._modal = $( "<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>" ) .on( "mousedown", function() { self.close(); }) .appendTo( target ); }, _getPage: function() { var page = this._parentPage ? this._parentPage : $( "." + $.mobile.activePageClass ); return page; }, _getWrapper: function() { var wrapper = this._page().find( "." + this.options.classes.pageWrapper ); if ( wrapper.length === 0 ) { wrapper = this._page().children( ".ui-header:not(.ui-header-fixed), .ui-content:not(.ui-popup), .ui-footer:not(.ui-footer-fixed)" ) .wrapAll( "<div class='" + this.options.classes.pageWrapper + "'></div>" ) .parent(); } return wrapper; }, _getFixedToolbars: function() { var extFixedToolbars = $( "body" ).children( ".ui-header-fixed, .ui-footer-fixed" ), intFixedToolbars = this._page().find( ".ui-header-fixed, .ui-footer-fixed" ), fixedToolbars = extFixedToolbars.add( intFixedToolbars ).addClass( this.options.classes.pageFixedToolbar ); return fixedToolbars; }, _getPosDisplayClasses: function( prefix ) { return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display; }, _getPanelClasses: function() { var panelClasses = this.options.classes.panel + " " + this._getPosDisplayClasses( this.options.classes.panel ) + " " + this.options.classes.panelClosed + " " + "ui-body-" + ( this.options.theme ? this.options.theme : "inherit" ); if ( !!this.options.positionFixed ) { panelClasses += " " + this.options.classes.panelFixed; } return panelClasses; }, _addPanelClasses: function() { this.element.addClass( this._getPanelClasses() ); }, _handleCloseClickAndEatEvent: function( event ) { if ( !event.isDefaultPrevented() ) { event.preventDefault(); this.close(); return false; } }, _handleCloseClick: function( event ) { if ( !event.isDefaultPrevented() ) { this.close(); } }, _bindCloseEvents: function() { this._on( this._closeLink, { "click": "_handleCloseClick" }); this._on({ "click a:jqmData(ajax='false')": "_handleCloseClick" }); }, _positionPanel: function() { var self = this, panelInnerHeight = self._panelInner.outerHeight(), expand = panelInnerHeight > $.mobile.getScreenHeight(); if ( expand || !self.options.positionFixed ) { if ( expand ) { self._unfixPanel(); $.mobile.resetActivePageHeight( panelInnerHeight ); } window.scrollTo( 0, $.mobile.defaultHomeScroll ); } else { self._fixPanel(); } }, _bindFixListener: function() { this._on( $( window ), { "throttledresize": "_positionPanel" }); }, _unbindFixListener: function() { this._off( $( window ), "throttledresize" ); }, _unfixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.removeClass( this.options.classes.panelFixed ); } }, _fixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.addClass( this.options.classes.panelFixed ); } }, _bindUpdateLayout: function() { var self = this; self.element.on( "updatelayout", function(/* e */) { if ( self._open ) { self._positionPanel(); } }); }, _bindLinkListeners: function() { this._on( "body", { "click a": "_handleClick" }); }, _handleClick: function( e ) { if ( e.currentTarget.href.split( "#" )[ 1 ] === this._panelID && this._panelID !== undefined ) { e.preventDefault(); var link = $( e.target ); if ( link.hasClass( "ui-btn" ) ) { link.addClass( $.mobile.activeBtnClass ); this.element.one( "panelopen panelclose", function() { link.removeClass( $.mobile.activeBtnClass ); }); } this.toggle(); return false; } }, _bindSwipeEvents: function() { var self = this, area = self._modal ? self.element.add( self._modal ) : self.element; // on swipe, close the panel if ( !!self.options.swipeClose ) { if ( self.options.position === "left" ) { area.on( "swipeleft.panel", function(/* e */) { self.close(); }); } else { area.on( "swiperight.panel", function(/* e */) { self.close(); }); } } }, _bindPageEvents: function() { var self = this; this.document // Close the panel if another panel on the page opens .on( "panelbeforeopen", function( e ) { if ( self._open && e.target !== self.element[ 0 ] ) { self.close(); } }) // On escape, close? might need to have a target check too... .on( "keyup.panel", function( e ) { if ( e.keyCode === 27 && self._open ) { self.close(); } }); // Clean up open panels after page hide if ( self._parentPage ) { this.document.on( "pagehide", ":jqmData(role='page')", function() { if ( self._open ) { self.close( true ); } }); } else { this.document.on( "pagebeforehide", function() { if ( self._open ) { self.close( true ); } }); } }, // state storage of open or closed _open: false, _pageContentOpenClasses: null, _modalOpenClasses: null, open: function( immediate ) { if ( !this._open ) { var self = this, o = self.options, _openPanel = function() { self.document.off( "panelclose" ); self._page().jqmData( "panel", "open" ); if ( $.support.cssTransform3d && !!o.animate && o.display !== "overlay" ) { self._wrapper().addClass( o.classes.animate ); self._fixedToolbars().addClass( o.classes.animate ); } if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.animationComplete( complete, "transition" ); } else { setTimeout( complete, 0 ); } if ( o.theme && o.display !== "overlay" ) { self._page().parent() .addClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } self.element .removeClass( o.classes.panelClosed ) .addClass( o.classes.panelOpen ); self._positionPanel(); self._pageContentOpenClasses = self._getPosDisplayClasses( o.classes.pageContentPrefix ); if ( o.display !== "overlay" ) { self._page().parent().addClass( o.classes.pageContainer ); self._wrapper().addClass( self._pageContentOpenClasses ); self._fixedToolbars().addClass( self._pageContentOpenClasses ); } self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen; if ( self._modal ) { self._modal .addClass( self._modalOpenClasses ) .height( Math.max( self._modal.height(), self.document.height() ) ); } }, complete = function() { if ( o.display !== "overlay" ) { self._wrapper().addClass( o.classes.pageContentPrefix + "-open" ); self._fixedToolbars().addClass( o.classes.pageContentPrefix + "-open" ); } self._bindFixListener(); self._trigger( "open" ); }; self._trigger( "beforeopen" ); if ( self._page().jqmData( "panel" ) === "open" ) { self.document.on( "panelclose", function() { _openPanel(); }); } else { _openPanel(); } self._open = true; } }, close: function( immediate ) { if ( this._open ) { var self = this, o = this.options, _closePanel = function() { self.element.removeClass( o.classes.panelOpen ); if ( o.display !== "overlay" ) { self._wrapper().removeClass( self._pageContentOpenClasses ); self._fixedToolbars().removeClass( self._pageContentOpenClasses ); } if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.animationComplete( complete, "transition" ); } else { setTimeout( complete, 0 ); } if ( self._modal ) { self._modal.removeClass( self._modalOpenClasses ); } }, complete = function() { if ( o.theme && o.display !== "overlay" ) { self._page().parent().removeClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } self.element.addClass( o.classes.panelClosed ); if ( o.display !== "overlay" ) { self._page().parent().removeClass( o.classes.pageContainer ); self._wrapper().removeClass( o.classes.pageContentPrefix + "-open" ); self._fixedToolbars().removeClass( o.classes.pageContentPrefix + "-open" ); } if ( $.support.cssTransform3d && !!o.animate && o.display !== "overlay" ) { self._wrapper().removeClass( o.classes.animate ); self._fixedToolbars().removeClass( o.classes.animate ); } self._fixPanel(); self._unbindFixListener(); $.mobile.resetActivePageHeight(); self._page().jqmRemoveData( "panel" ); self._trigger( "close" ); }; self._trigger( "beforeclose" ); _closePanel(); self._open = false; } }, toggle: function() { this[ this._open ? "close" : "open" ](); }, _destroy: function() { var otherPanels, o = this.options, multiplePanels = ( $( "body > :mobile-panel" ).length + $.mobile.activePage.find( ":mobile-panel" ).length ) > 1; if ( o.display !== "overlay" ) { // remove the wrapper if not in use by another panel otherPanels = $( "body > :mobile-panel" ).add( $.mobile.activePage.find( ":mobile-panel" ) ); if ( otherPanels.not( ".ui-panel-display-overlay" ).not( this.element ).length === 0 ) { this._wrapper().children().unwrap(); } if ( this._open ) { this._fixedToolbars().removeClass( o.classes.pageContentPrefix + "-open" ); if ( $.support.cssTransform3d && !!o.animate ) { this._fixedToolbars().removeClass( o.classes.animate ); } this._page().parent().removeClass( o.classes.pageContainer ); if ( o.theme ) { this._page().parent().removeClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } } } if ( !multiplePanels ) { this.document.off( "panelopen panelclose" ); } if ( this._open ) { this._page().jqmRemoveData( "panel" ); } this._panelInner.children().unwrap(); this.element .removeClass( [ this._getPanelClasses(), o.classes.panelOpen, o.classes.animate ].join( " " ) ) .off( "swipeleft.panel swiperight.panel" ) .off( "panelbeforeopen" ) .off( "panelhide" ) .off( "keyup.panel" ) .off( "updatelayout" ); if ( this._modal ) { this._modal.remove(); } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", { options: { classes: { table: "ui-table" }, enhanced: false }, _create: function() { if ( !this.options.enhanced ) { this.element.addClass( this.options.classes.table ); } // extend here, assign on refresh > _setHeaders $.extend( this, { // Expose headers and allHeaders properties on the widget // headers references the THs within the first TR in the table headers: undefined, // allHeaders references headers, plus all THs in the thead, which may // include several rows, or not allHeaders: undefined }); this._refresh( true ); }, _setHeaders: function() { var trs = this.element.find( "thead tr" ); this.headers = this.element.find( "tr:eq(0)" ).children(); this.allHeaders = this.headers.add( trs.children() ); }, refresh: function() { this._refresh(); }, rebuild: $.noop, _refresh: function( /* create */ ) { var table = this.element, trs = table.find( "thead tr" ); // updating headers on refresh (fixes #5880) this._setHeaders(); // Iterate over the trs trs.each( function() { var columnCount = 0; // Iterate over the children of the tr $( this ).children().each( function() { var span = parseInt( this.getAttribute( "colspan" ), 10 ), selector = ":nth-child(" + ( columnCount + 1 ) + ")", j; this.setAttribute( "data-" + $.mobile.ns + "colstart", columnCount + 1 ); if ( span ) { for( j = 0; j < span - 1; j++ ) { columnCount++; selector += ", :nth-child(" + ( columnCount + 1 ) + ")"; } } // Store "cells" data on header as a reference to all cells in the // same column as this TH $( this ).jqmData( "cells", table.find( "tr" ).not( trs.eq( 0 ) ).not( this ).children( selector ) ); columnCount++; }); }); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", $.mobile.table, { options: { mode: "columntoggle", columnBtnTheme: null, columnPopupTheme: null, columnBtnText: "Columns...", classes: $.extend( $.mobile.table.prototype.options.classes, { popup: "ui-table-columntoggle-popup", columnBtn: "ui-table-columntoggle-btn", priorityPrefix: "ui-table-priority-", columnToggleTable: "ui-table-columntoggle" }) }, _create: function() { this._super(); if ( this.options.mode !== "columntoggle" ) { return; } $.extend( this, { _menu: null }); if ( this.options.enhanced ) { this._menu = $( this.document[ 0 ].getElementById( this._id() + "-popup" ) ).children().first(); this._addToggles( this._menu, true ); } else { this._menu = this._enhanceColToggle(); this.element.addClass( this.options.classes.columnToggleTable ); } this._setupEvents(); this._setToggleState(); }, _id: function() { return ( this.element.attr( "id" ) || ( this.widgetName + this.uuid ) ); }, _setupEvents: function() { //NOTE: inputs are bound in bindToggles, // so it can be called on refresh, too // update column toggles on resize this._on( this.window, { throttledresize: "_setToggleState" }); this._on( this._menu, { "change input": "_menuInputChange" }); }, _addToggles: function( menu, keep ) { var inputs, checkboxIndex = 0, opts = this.options, container = menu.controlgroup( "container" ); // allow update of menu on refresh (fixes #5880) if ( keep ) { inputs = menu.find( "input" ); } else { container.empty(); } // create the hide/show toggles this.headers.not( "td" ).each( function() { var header = $( this ), priority = $.mobile.getAttribute( this, "priority" ), cells = header.add( header.jqmData( "cells" ) ); if ( priority ) { cells.addClass( opts.classes.priorityPrefix + priority ); ( keep ? inputs.eq( checkboxIndex++ ) : $("<label><input type='checkbox' checked />" + ( header.children( "abbr" ).first().attr( "title" ) || header.text() ) + "</label>" ) .appendTo( container ) .children( 0 ) .checkboxradio( { theme: opts.columnPopupTheme }) ) .jqmData( "cells", cells ); } }); // set bindings here if ( !keep ) { menu.controlgroup( "refresh" ); } }, _menuInputChange: function( evt ) { var input = $( evt.target ), checked = input[ 0 ].checked; input.jqmData( "cells" ) .toggleClass( "ui-table-cell-hidden", !checked ) .toggleClass( "ui-table-cell-visible", checked ); if ( input[ 0 ].getAttribute( "locked" ) ) { input.removeAttr( "locked" ); this._unlockCells( input.jqmData( "cells" ) ); } else { input.attr( "locked", true ); } }, _unlockCells: function( cells ) { // allow hide/show via CSS only = remove all toggle-locks cells.removeClass( "ui-table-cell-hidden ui-table-cell-visible"); }, _enhanceColToggle: function() { var id , menuButton, popup, menu, table = this.element, opts = this.options, ns = $.mobile.ns, fragment = this.document[ 0 ].createDocumentFragment(); id = this._id() + "-popup"; menuButton = $( "<a href='#" + id + "' " + "class='" + opts.classes.columnBtn + " ui-btn " + "ui-btn-" + ( opts.columnBtnTheme || "a" ) + " ui-corner-all ui-shadow ui-mini' " + "data-" + ns + "rel='popup'>" + opts.columnBtnText + "</a>" ); popup = $( "<div class='" + opts.classes.popup + "' id='" + id + "'></div>" ); menu = $( "<fieldset></fieldset>" ).controlgroup(); // set extension here, send "false" to trigger build/rebuild this._addToggles( menu, false ); menu.appendTo( popup ); fragment.appendChild( popup[ 0 ] ); fragment.appendChild( menuButton[ 0 ] ); table.before( fragment ); popup.popup(); return menu; }, rebuild: function() { this._super(); if ( this.options.mode === "columntoggle" ) { // NOTE: rebuild passes "false", while refresh passes "undefined" // both refresh the table, but inside addToggles, !false will be true, // so a rebuild call can be indentified this._refresh( false ); } }, _refresh: function( create ) { this._super( create ); if ( !create && this.options.mode === "columntoggle" ) { // columns not being replaced must be cleared from input toggle-locks this._unlockCells( this.allHeaders ); // update columntoggles and cells this._addToggles( this._menu, create ); // check/uncheck this._setToggleState(); } }, _setToggleState: function() { this._menu.find( "input" ).each( function() { var checkbox = $( this ); this.checked = checkbox.jqmData( "cells" ).eq( 0 ).css( "display" ) === "table-cell"; checkbox.checkboxradio( "refresh" ); }); }, _destroy: function() { this._super(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", $.mobile.table, { options: { mode: "reflow", classes: $.extend( $.mobile.table.prototype.options.classes, { reflowTable: "ui-table-reflow", cellLabels: "ui-table-cell-label" }) }, _create: function() { this._super(); // If it's not reflow mode, return here. if ( this.options.mode !== "reflow" ) { return; } if ( !this.options.enhanced ) { this.element.addClass( this.options.classes.reflowTable ); this._updateReflow(); } }, rebuild: function() { this._super(); if ( this.options.mode === "reflow" ) { this._refresh( false ); } }, _refresh: function( create ) { this._super( create ); if ( !create && this.options.mode === "reflow" ) { this._updateReflow( ); } }, _updateReflow: function() { var table = this, opts = this.options; // get headers in reverse order so that top-level headers are appended last $( table.allHeaders.get().reverse() ).each( function() { var cells = $( this ).jqmData( "cells" ), colstart = $.mobile.getAttribute( this, "colstart" ), hierarchyClass = cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top", text = $( this ).text(), iteration, filter; if ( text !== "" ) { if ( hierarchyClass ) { iteration = parseInt( this.getAttribute( "colspan" ), 10 ); filter = ""; if ( iteration ) { filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")"; } table._addLabels( cells.filter( filter ), opts.classes.cellLabels + hierarchyClass, text ); } else { table._addLabels( cells, opts.classes.cellLabels, text ); } } }); }, _addLabels: function( cells, label, text ) { // .not fixes #6006 cells.not( ":has(b." + label + ")" ).prepend( "<b class='" + label + "'>" + text + "</b>" ); } }); })( jQuery ); (function( $, undefined ) { // TODO rename filterCallback/deprecate and default to the item itself as the first argument var defaultFilterCallback = function( index, searchValue ) { return ( ( "" + ( $.mobile.getAttribute( this, "filtertext" ) || $( this ).text() ) ) .toLowerCase().indexOf( searchValue ) === -1 ); }; $.widget( "mobile.filterable", { initSelector: ":jqmData(filter='true')", options: { filterReveal: false, filterCallback: defaultFilterCallback, enhanced: false, input: null, children: "> li, > option, > optgroup option, > tbody tr, > .ui-controlgroup-controls > .ui-btn, > .ui-controlgroup-controls > .ui-checkbox, > .ui-controlgroup-controls > .ui-radio" }, _create: function() { var opts = this.options; $.extend( this, { _search: null, _timer: 0 }); this._setInput( opts.input ); if ( !opts.enhanced ) { this._filterItems( ( ( this._search && this._search.val() ) || "" ).toLowerCase() ); } }, _onKeyUp: function() { var val, lastval, search = this._search; if ( search ) { val = search.val().toLowerCase(), lastval = $.mobile.getAttribute( search[ 0 ], "lastval" ) + ""; if ( lastval && lastval === val ) { // Execute the handler only once per value change return; } if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } this._timer = this._delay( function() { this._trigger( "beforefilter", null, { input: search } ); // Change val as lastval for next execution search[ 0 ].setAttribute( "data-" + $.mobile.ns + "lastval", val ); this._filterItems( val ); this._timer = 0; }, 250 ); } }, _getFilterableItems: function() { var elem = this.element, children = this.options.children, items = !children ? { length: 0 }: $.isFunction( children ) ? children(): children.nodeName ? $( children ): children.jquery ? children: this.element.find( children ); if ( items.length === 0 ) { items = elem.children(); } return items; }, _filterItems: function( val ) { var idx, callback, length, dst, show = [], hide = [], opts = this.options, filterItems = this._getFilterableItems(); if ( val != null ) { callback = opts.filterCallback || defaultFilterCallback; length = filterItems.length; // Partition the items into those to be hidden and those to be shown for ( idx = 0 ; idx < length ; idx++ ) { dst = ( callback.call( filterItems[ idx ], idx, val ) ) ? hide : show; dst.push( filterItems[ idx ] ); } } // If nothing is hidden, then the decision whether to hide or show the items // is based on the "filterReveal" option. if ( hide.length === 0 ) { filterItems[ opts.filterReveal ? "addClass" : "removeClass" ]( "ui-screen-hidden" ); } else { $( hide ).addClass( "ui-screen-hidden" ); $( show ).removeClass( "ui-screen-hidden" ); } this._refreshChildWidget(); this._trigger( "filter", null, { items: filterItems }); }, // The Default implementation of _refreshChildWidget attempts to call // refresh on collapsibleset, controlgroup, selectmenu, or listview _refreshChildWidget: function() { var widget, idx, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ]; for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widget = recognizedWidgets[ idx ]; if ( $.mobile[ widget ] ) { widget = this.element.data( "mobile-" + widget ); if ( widget && $.isFunction( widget.refresh ) ) { widget.refresh(); } } } }, // TODO: When the input is not internal, do not even store it in this._search _setInput: function ( selector ) { var search = this._search; // Stop a pending filter operation if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } if ( search ) { this._off( search, "keyup change input" ); search = null; } if ( selector ) { search = selector.jquery ? selector: selector.nodeName ? $( selector ): this.document.find( selector ); this._on( search, { keyup: "_onKeyUp", change: "_onKeyUp", input: "_onKeyUp" }); } this._search = search; }, _setOptions: function( options ) { var refilter = !( ( options.filterReveal === undefined ) && ( options.filterCallback === undefined ) && ( options.children === undefined ) ); this._super( options ); if ( options.input !== undefined ) { this._setInput( options.input ); refilter = true; } if ( refilter ) { this.refresh(); } }, _destroy: function() { var opts = this.options, items = this._getFilterableItems(); if ( opts.enhanced ) { items.toggleClass( "ui-screen-hidden", opts.filterReveal ); } else { items.removeClass( "ui-screen-hidden" ); } }, refresh: function() { if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } this._filterItems( ( ( this._search && this._search.val() ) || "" ).toLowerCase() ); } }); })( jQuery ); (function( $, undefined ) { // Create a function that will replace the _setOptions function of a widget, // and will pass the options on to the input of the filterable. var replaceSetOptions = function( self, orig ) { return function( options ) { orig.call( this, options ); self._syncTextInputOptions( options ); }; }, rDividerListItem = /(^|\s)ui-li-divider(\s|$)/, origDefaultFilterCallback = $.mobile.filterable.prototype.options.filterCallback; // Override the default filter callback with one that does not hide list dividers $.mobile.filterable.prototype.options.filterCallback = function( index, searchValue ) { return !this.className.match( rDividerListItem ) && origDefaultFilterCallback.call( this, index, searchValue ); }; $.widget( "mobile.filterable", $.mobile.filterable, { options: { filterPlaceholder: "Filter items...", filterTheme: null }, _create: function() { var idx, widgetName, elem = this.element, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ], createHandlers = {}; this._super(); $.extend( this, { _widget: null }); for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widgetName = recognizedWidgets[ idx ]; if ( $.mobile[ widgetName ] ) { if ( this._setWidget( elem.data( "mobile-" + widgetName ) ) ) { break; } else { createHandlers[ widgetName + "create" ] = "_handleCreate"; } } } if ( !this._widget ) { this._on( elem, createHandlers ); } }, _handleCreate: function( evt ) { this._setWidget( this.element.data( "mobile-" + evt.type.substring( 0, evt.type.length - 6 ) ) ); }, _trigger: function( type, event, data ) { if ( this._widget && this._widget.widgetFullName === "mobile-listview" && type === "beforefilter" ) { // Also trigger listviewbeforefilter if this widget is also a listview this._widget._trigger( "beforefilter", event, data ); } this._super( type, event, data ); }, _setWidget: function( widget ) { if ( !this._widget && widget ) { this._widget = widget; this._widget._setOptions = replaceSetOptions( this, this._widget._setOptions ); } if ( !!this._widget ) { this._syncTextInputOptions( this._widget.options ); if ( this._widget.widgetName === "listview" ) { this._widget.options.hideDividers = true; this._widget.element.listview( "refresh" ); } } return !!this._widget; }, _isSearchInternal: function() { return ( this._search && this._search.jqmData( "ui-filterable-" + this.uuid + "-internal" ) ); }, _setInput: function( selector ) { var opts = this.options, updatePlaceholder = true, textinputOpts = {}; if ( !selector ) { if ( this._isSearchInternal() ) { // Ignore the call to set a new input if the selector goes to falsy and // the current textinput is already of the internally generated variety. return; } else { // Generating a new textinput widget. No need to set the placeholder // further down the function. updatePlaceholder = false; selector = $( "<input " + "data-" + $.mobile.ns + "type='search' " + "placeholder='" + opts.filterPlaceholder + "'></input>" ) .jqmData( "ui-filterable-" + this.uuid + "-internal", true ); $( "<form class='ui-filterable'></form>" ) .append( selector ) .submit( function( evt ) { evt.preventDefault(); selector.blur(); }) .insertBefore( this.element ); if ( $.mobile.textinput ) { if ( this.options.filterTheme != null ) { textinputOpts[ "theme" ] = opts.filterTheme; } selector.textinput( textinputOpts ); } } } this._super( selector ); if ( this._isSearchInternal() && updatePlaceholder ) { this._search.attr( "placeholder", this.options.filterPlaceholder ); } }, _setOptions: function( options ) { var ret = this._super( options ); // Need to set the filterPlaceholder after having established the search input if ( options.filterPlaceholder !== undefined ) { if ( this._isSearchInternal() ) { this._search.attr( "placeholder", options.filterPlaceholder ); } } if ( options.filterTheme !== undefined && this._search && $.mobile.textinput ) { this._search.textinput( "option", "theme", options.filterTheme ); } return ret; }, _destroy: function() { if ( this._isSearchInternal() ) { this._search.remove(); } this._super(); }, _syncTextInputOptions: function( options ) { var idx, textinputOptions = {}; // We only sync options if the filterable's textinput is of the internally // generated variety, rather than one specified by the user. if ( this._isSearchInternal() && $.mobile.textinput ) { // Apply only the options understood by textinput for ( idx in $.mobile.textinput.prototype.options ) { if ( options[ idx ] !== undefined ) { if ( idx === "theme" && this.options.filterTheme != null ) { textinputOptions[ idx ] = this.options.filterTheme; } else { textinputOptions[ idx ] = options[ idx ]; } } } this._search.textinput( "option", textinputOptions ); } } }); })( jQuery ); /*! * jQuery UI Tabs fadf2b312a05040436451c64bbfaf4814bc62c56 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tabs/ * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var tabId = 0, rhash = /#.*$/; function getNextTabId() { return ++tabId; } function isLocal( anchor ) { return anchor.hash.length > 1 && decodeURIComponent( anchor.href.replace( rhash, "" ) ) === decodeURIComponent( location.href.replace( rhash, "" ) ); } $.widget( "ui.tabs", { version: "fadf2b312a05040436451c64bbfaf4814bc62c56", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _tabId: function( tab ) { return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId(); }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-expanded": "false", "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( isLocal( anchor ) ) { selector = anchor.hash; panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { panelId = that._tabId( tab ); selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": selector.substring( 1 ), "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = { click: function( event ) { event.preventDefault(); } }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); eventData.oldTab.attr( "aria-selected", "false" ); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr({ "aria-expanded": "true", "aria-hidden": "false" }); eventData.newTab.attr({ "aria-selected": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); })( jQuery ); (function( $, undefined ) { })( jQuery ); (function( $, window ) { $.mobile.iosorientationfixEnabled = true; // This fix addresses an iOS bug, so return early if the UA claims it's something else. var ua = navigator.userAgent, zoom, evt, x, y, z, aig; if ( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ) { $.mobile.iosorientationfixEnabled = false; return; } zoom = $.mobile.zoom; function checkTilt( e ) { evt = e.originalEvent; aig = evt.accelerationIncludingGravity; x = Math.abs( aig.x ); y = Math.abs( aig.y ); z = Math.abs( aig.z ); // If portrait orientation and in one of the danger zones if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) { if ( zoom.enabled ) { zoom.disable(); } } else if ( !zoom.enabled ) { zoom.enable(); } } $.mobile.document.on( "mobileinit", function() { if ( $.mobile.iosorientationfixEnabled ) { $.mobile.window .bind( "orientationchange.iosorientationfix", zoom.enable ) .bind( "devicemotion.iosorientationfix", checkTilt ); } }); }( jQuery, this )); (function( $, window, undefined ) { var $html = $( "html" ), $window = $.mobile.window; //remove initial build class (only present on first pageshow) function hideRenderingClass() { $html.removeClass( "ui-mobile-rendering" ); } // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); // support conditions // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, // otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if ( $.mobile.ajaxBlacklist ) { $.mobile.ajaxEnabled = false; } // Add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); // This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire, // this ensures the rendering class is removed after 5 seconds, so content is visible and accessible setTimeout( hideRenderingClass, 5000 ); $.extend( $.mobile, { // find and enhance the pages in the dom and transition to the first page. initializePage: function() { // find present pages var path = $.mobile.path, $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ), hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ), hashPage = document.getElementById( hash ); // if no pages are found, create one with body's inner html if ( !$pages.length ) { $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } // add dialogs, set data-url attrs $pages.each(function() { var $this = $( this ); // unless the data url is already set set it to the pathname if ( !$this[ 0 ].getAttribute( "data-" + $.mobile.ns + "url" ) ) { $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search ); } }); // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); // define page container $.mobile.pageContainer = $.mobile.firstPage .parent() .addClass( "ui-mobile-viewport" ) .pagecontainer(); // initialize navigation events now, after mobileinit has occurred and the page container // has been created but before the rest of the library is alerted to that fact $.mobile.navreadyDeferred.resolve(); // alert listeners that the pagecontainer has been determined for binding // to events triggered on it $window.trigger( "pagecontainercreate" ); // cue page loading message $.mobile.loading( "show" ); //remove initial build class (only present on first pageshow) hideRenderingClass(); // if hashchange listening is disabled, there's no hash deeplink, // the hash is not valid (contains more than one # or does not start with #) // or there is no page with that hash, change to the first page in the DOM // Remember, however, that the hash can also be a path! if ( ! ( $.mobile.hashListeningEnabled && $.mobile.path.isHashValid( location.hash ) && ( $( hashPage ).is( ":jqmData(role='page')" ) || $.mobile.path.isPath( hash ) || hash === $.mobile.dialogHashKey ) ) ) { // Store the initial destination if ( $.mobile.path.isHashValid( location.hash ) ) { $.mobile.navigate.history.initialDst = hash.replace( "#", "" ); } // make sure to set initial popstate state if it exists // so that navigation back to the initial page works properly if ( $.event.special.navigate.isPushStateEnabled() ) { $.mobile.navigate.navigator.squash( path.parseLocation().href ); } $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true }); } else { // trigger hashchange or navigate to squash and record the correct // history entry for an initial hash path if ( !$.event.special.navigate.isPushStateEnabled() ) { $window.trigger( "hashchange", [true] ); } else { // TODO figure out how to simplify this interaction with the initial history entry // at the bottom js/navigate/navigate.js $.mobile.navigate.history.stack = []; $.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href ); } } } }); $(function() { //Run inlineSVG support test $.support.inlineSVG(); // check which scrollTop value should be used by scrolling to 1 immediately at domready // then check what the scroll top is. Android will report 0... others 1 // note that this initial scroll won't hide the address bar. It's just for the check. // hide iOS browser chrome on load if hideUrlBar is true this is to try and do it as soon as possible if ( $.mobile.hideUrlBar ) { window.scrollTo( 0, 1 ); } // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) // so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if ( $.mobile.autoInitializePage ) { $.mobile.initializePage(); } // window load event // hide iOS browser chrome on load if hideUrlBar is true this is as fall back incase we were too early before if ( $.mobile.hideUrlBar ) { $window.load( $.mobile.silentScroll ); } if ( !$.support.cssPointerEvents ) { // IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons // by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser. // https://github.com/jquery/jquery-mobile/issues/3558 // DEPRECATED as of 1.4.0 - remove ui-disabled after 1.4.0 release // only ui-state-disabled should be present thereafter $.mobile.document.delegate( ".ui-state-disabled,.ui-disabled", "vclick", function( e ) { e.preventDefault(); e.stopImmediatePropagation(); } ); } }); }( jQuery, this )); }));
src/components/Roll.js
cannc4/Siren
import _ from 'lodash'; import React from 'react'; import { inject, observer } from 'mobx-react'; import timeLoop from '../utils/timeLoop'; import rollStore from '../stores/rollStore'; class RollCanvas extends React.Component { render() { // console.log("RENDER CANVASLOOP"); rollStore.value_time = this.props.time / 1000.; rollStore.cleanData(); rollStore.renderCanvas(); return ( <div className={'CanvasSketch'}> <canvas id="pat_roll" width={'100'} height={'100'}></canvas> </div> ); } }; const RollLoop = timeLoop(RollCanvas); @inject('rollStore') @observer export default class Roll extends React.Component { render() { console.log("RENDER CANVAS.JS"); return (<div className={"Canvas"}> <RollLoop></RollLoop> </div>); } }
src/containers/Playground/TimeBar/index.js
mmazzarolo/tap-the-number
/* @flow */ /** * The time left bar at the top of the Playground screen. */ import React, { Component } from 'react'; import { View } from 'react-native-animatable'; import { Animated, Easing } from 'react-native'; import styles from './index.style'; import metrics from 'src/config/metrics'; import timings from 'src/config/timings'; type State = { animateValue: any, }; export default class TimeBar extends Component<void, {}, State> { state = { animateValue: new Animated.Value(timings.TIME_LIMIT_MS), }; componentDidMount() { Animated.timing(this.state.animateValue, { duration: timings.TIME_LIMIT_MS, easing: Easing.linear, // No easing toValue: 0, }).start(); } render() { // Animate the TimeBar color from grey to red, starting when there are left only 12 seconds const backgroundColor = this.state.animateValue.interpolate({ inputRange: [0, timings.TIME_LIMIT_MS * 0.4, timings.TIME_LIMIT_MS], outputRange: ['rgba(255,0,0, 1)', 'rgba(0,0,0, 0.3)', 'rgba(0,0,0, 0.3)'], }); // Animate the TimeBar width from DEVICE_WIDTH to 0 in TIME_LIMIT_MS (which currently is 30 seconds) const width = this.state.animateValue.interpolate({ inputRange: [0, timings.TIME_LIMIT_MS], outputRange: [0, metrics.DEVICE_WIDTH], }); return ( <View style={styles.container}> <View style={[styles.content, { width, backgroundColor }]} /> </View> ); } }
generators/app/templates/src/index.js
thisjeremiah/generator-react-options
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { ConnectedRouter } from 'react-router-redux' import 'semantic-ui-css/semantic.min.css' import './configureRx' import App from './App' import registerServiceWorker from './registerServiceWorker' import store, { history } from './createStore' import './index.css' const render = Component => { ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <Component /> </ConnectedRouter> </Provider>, document.getElementById('root') ) } render(App) registerServiceWorker() if (module.hot) { module.hot.accept('./App', () => { const NextApp = require('./App').default render(NextApp) }) }
docs/pages/_document.js
kybarg/material-ui
/* eslint-disable no-underscore-dangle */ import React from 'react'; import { ServerStyleSheets } from '@material-ui/styles'; import Document, { Head, Main, NextScript } from 'next/document'; import { Router as Router2 } from 'next/router'; import { LANGUAGES_SSR } from 'docs/src/modules/constants'; import { pathnameToLanguage } from 'docs/src/modules/utils/helpers'; import { themeColor } from 'docs/src/modules/components/ThemeContext'; // You can find a benchmark of the available CSS minifiers under // https://github.com/GoalSmashers/css-minification-benchmark // We have found that clean-css is faster than cssnano but the output is larger. // Waiting for https://github.com/cssinjs/jss/issues/279 // 4% slower but 12% smaller output than doing it in a single step. // // It's using .browserslistrc let prefixer; let cleanCSS; if (process.env.NODE_ENV === 'production') { /* eslint-disable global-require */ const postcss = require('postcss'); const autoprefixer = require('autoprefixer'); const CleanCSS = require('clean-css'); /* eslint-enable global-require */ prefixer = postcss([autoprefixer]); cleanCSS = new CleanCSS(); } const GOOGLE_ID = process.env.NODE_ENV === 'production' ? 'UA-106598593-2' : 'UA-106598593-3'; class MyDocument extends Document { render() { const { canonical, userLanguage } = this.props; return ( <html lang={userLanguage}> <Head> {/* Use minimum-scale=1 to enable GPU rasterization. */} <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no" /> {/* manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ */} <link rel="manifest" href="/static/manifest.json" /> {/* PWA primary color */} <meta name="theme-color" content={themeColor} /> <link rel="shortcut icon" href="/static/favicon.ico" /> {/* iOS Icon */} <link rel="apple-touch-icon" sizes="180x180" href="/static/icons/180x180.png" /> {/* SEO */} <link rel="canonical" href={`https://material-ui.com${Router2._rewriteUrlForNextExport( `${userLanguage === 'en' ? '' : `/${userLanguage}`}${canonical}`, )}`} /> <link rel="alternate" href={`https://material-ui.com${Router2._rewriteUrlForNextExport(canonical)}`} hrefLang="x-default" /> {LANGUAGES_SSR.map(userLanguage2 => ( <link key={userLanguage2} rel="alternate" href={`https://material-ui.com${Router2._rewriteUrlForNextExport( `${userLanguage2 === 'en' ? '' : `/${userLanguage2}`}${canonical}`, )}`} hrefLang={userLanguage2} /> ))} {/* Preconnect allows the browser to setup early connections before an HTTP request is actually sent to the server. This includes DNS lookups, TLS negotiations, TCP handshakes. */} <link href="https://fonts.gstatic.com" rel="preconnect" crossOrigin="anonymous" /> <style id="material-icon-font" /> <style id="font-awesome-css" /> <style id="app-search" /> <style id="prismjs" /> <style id="insertion-point-jss" /> </Head> <body> <Main /> <script // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: ` window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; window.ga('create','${GOOGLE_ID}','auto'); `, }} /> <NextScript /> </body> </html> ); } } MyDocument.getInitialProps = async ctx => { // Resolution order // // On the server: // 1. page.getInitialProps // 2. document.getInitialProps // 3. page.render // 4. document.render // // On the server with error: // 2. document.getInitialProps // 3. page.render // 4. document.render // // On the client // 1. page.getInitialProps // 3. page.render // Render app and page and get the context of the page with collected side effects. const sheets = new ServerStyleSheets(); const originalRenderPage = ctx.renderPage; ctx.renderPage = () => originalRenderPage({ enhanceApp: App => props => sheets.collect(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); let css = sheets.toString(); // It might be undefined, e.g. after an error. if (css && process.env.NODE_ENV === 'production') { const result1 = await prefixer.process(css, { from: undefined }); css = result1.css; css = cleanCSS.minify(css).styles; } return { ...initialProps, canonical: pathnameToLanguage(ctx.req.url).canonical, userLanguage: ctx.query.userLanguage || 'en', styles: ( <style id="jss-server-side" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: css }} /> ), }; }; export default MyDocument;
app.js
nick/react-skeleton
import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { render() { return <div>React Loaded OK!</div>; } } ReactDOM.render(<App />, document.getElementById('react'));
ajax/libs/cyclejs-dom/10.0.0-rc20/cycle-dom.js
dc-js/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.CycleDOM = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ "use strict"; var xstream_adapter_1 = require('@cycle/xstream-adapter'); var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null); var ElementFinder_1 = require('./ElementFinder'); var fromEvent_1 = require('./fromEvent'); var isolate_1 = require('./isolate'); var EventDelegator_1 = require('./EventDelegator'); var utils_1 = require('./utils'); var matchesSelector; try { matchesSelector = require("matches-selector"); } catch (e) { matchesSelector = Function.prototype; } var eventTypesThatDontBubble = ["load", "unload", "focus", "blur", "mouseenter", "mouseleave", "submit", "change", "reset", "timeupdate", "playing", "waiting", "seeking", "seeked", "ended", "loadedmetadata", "loadeddata", "canplay", "canplaythrough", "durationchange", "play", "pause", "ratechange", "volumechange", "suspend", "emptied", "stalled"]; function determineUseCapture(eventType, options) { var result = false; if (typeof options.useCapture === "boolean") { result = options.useCapture; } if (eventTypesThatDontBubble.indexOf(eventType) !== -1) { result = true; } return result; } var DOMSource = function () { function DOMSource(_rootElement$, _runStreamAdapter, _namespace, _isolateModule, _delegators) { if (_namespace === void 0) { _namespace = []; } this._rootElement$ = _rootElement$; this._runStreamAdapter = _runStreamAdapter; this._namespace = _namespace; this._isolateModule = _isolateModule; this._delegators = _delegators; this.isolateSource = isolate_1.isolateSource; this.isolateSink = isolate_1.isolateSink; } Object.defineProperty(DOMSource.prototype, "elements", { get: function get() { if (this._namespace.length === 0) { return this._runStreamAdapter.adapt(this._rootElement$, xstream_adapter_1.default.streamSubscribe); } else { var elementFinder_1 = new ElementFinder_1.ElementFinder(this._namespace, this._isolateModule); return this._runStreamAdapter.adapt(this._rootElement$.map(function (el) { return elementFinder_1.call(el); }), xstream_adapter_1.default.streamSubscribe); } }, enumerable: true, configurable: true }); Object.defineProperty(DOMSource.prototype, "namespace", { get: function get() { return this._namespace; }, enumerable: true, configurable: true }); DOMSource.prototype.select = function (selector) { if (typeof selector !== 'string') { throw new Error("DOM driver's select() expects the argument to be a " + "string as a CSS selector"); } var trimmedSelector = selector.trim(); var childNamespace = trimmedSelector === ":root" ? this._namespace : this._namespace.concat(trimmedSelector); return new DOMSource(this._rootElement$, this._runStreamAdapter, childNamespace, this._isolateModule, this._delegators); }; DOMSource.prototype.events = function (eventType, options) { if (options === void 0) { options = {}; } if (typeof eventType !== "string") { throw new Error("DOM driver's events() expects argument to be a " + "string representing the event type to listen for."); } var useCapture = determineUseCapture(eventType, options); var namespace = this._namespace; var scope = utils_1.getScope(namespace); var keyParts = [eventType, useCapture]; if (scope) { keyParts.push(scope); } var key = keyParts.join('~'); var domSource = this; var rootElement$; if (scope) { var hadIsolated_mutable_1 = false; rootElement$ = this._rootElement$.filter(function (rootElement) { var hasIsolated = !!domSource._isolateModule.getIsolatedElement(scope); var shouldPass = hasIsolated && !hadIsolated_mutable_1; hadIsolated_mutable_1 = hasIsolated; return shouldPass; }); } else { rootElement$ = this._rootElement$.take(2); } var event$ = rootElement$.map(function setupEventDelegatorOnTopElement(rootElement) { // Event listener just for the root element if (!namespace || namespace.length === 0) { return fromEvent_1.fromEvent(rootElement, eventType, useCapture); } // Event listener on the top element as an EventDelegator var delegators = domSource._delegators; var top = scope ? domSource._isolateModule.getIsolatedElement(scope) : rootElement; var delegator; if (delegators.has(key)) { delegator = delegators.get(key); delegator.updateTopElement(top); } else { delegator = new EventDelegator_1.EventDelegator(top, eventType, useCapture, domSource._isolateModule); delegators.set(key, delegator); } var subject = xstream_1.default.create(); if (scope) { domSource._isolateModule.addEventDelegator(scope, delegator); } delegator.addDestination(subject, namespace); return subject; }).flatten(); return this._runStreamAdapter.adapt(event$, xstream_adapter_1.default.streamSubscribe); }; DOMSource.prototype.dispose = function () { this._isolateModule.reset(); }; return DOMSource; }(); exports.DOMSource = DOMSource; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./ElementFinder":2,"./EventDelegator":3,"./fromEvent":6,"./isolate":10,"./utils":17,"@cycle/xstream-adapter":18,"matches-selector":39}],2:[function(require,module,exports){ "use strict"; var ScopeChecker_1 = require('./ScopeChecker'); var utils_1 = require('./utils'); var matchesSelector; try { matchesSelector = require("matches-selector"); } catch (e) { matchesSelector = Function.prototype; } function toElArray(input) { return Array.prototype.slice.call(input); } var ElementFinder = function () { function ElementFinder(namespace, isolateModule) { this.namespace = namespace; this.isolateModule = isolateModule; } ElementFinder.prototype.call = function (rootElement) { var namespace = this.namespace; if (namespace.join("") === "") { return rootElement; } var scope = utils_1.getScope(namespace); var scopeChecker = new ScopeChecker_1.ScopeChecker(scope, this.isolateModule); var selector = utils_1.getSelectors(namespace); var topNode = rootElement; var topNodeMatches = []; if (scope.length > 0) { topNode = this.isolateModule.getIsolatedElement(scope) || rootElement; if (selector && matchesSelector(topNode, selector)) { topNodeMatches.push(topNode); } } return toElArray(topNode.querySelectorAll(selector)).filter(scopeChecker.isStrictlyInRootScope, scopeChecker).concat(topNodeMatches); }; return ElementFinder; }(); exports.ElementFinder = ElementFinder; },{"./ScopeChecker":4,"./utils":17,"matches-selector":39}],3:[function(require,module,exports){ "use strict"; var ScopeChecker_1 = require('./ScopeChecker'); var utils_1 = require('./utils'); var matchesSelector; try { matchesSelector = require("matches-selector"); } catch (e) { matchesSelector = Function.prototype; } /** * Attaches an actual event listener to the DOM root element, * handles "destinations" (interested DOMSource output subjects), and bubbling. */ var EventDelegator = function () { function EventDelegator(topElement, eventType, useCapture, isolateModule) { var _this = this; this.topElement = topElement; this.eventType = eventType; this.useCapture = useCapture; this.isolateModule = isolateModule; this.destinations = []; this.roof = topElement.parentElement; if (useCapture) { this.domListener = function (ev) { return _this.capture(ev); }; } else { this.domListener = function (ev) { return _this.bubble(ev); }; } topElement.addEventListener(eventType, this.domListener, useCapture); } EventDelegator.prototype.bubble = function (rawEvent) { if (!document.body.contains(rawEvent.currentTarget)) { return; } var ev = this.patchEvent(rawEvent); for (var el = ev.target; el && el !== this.roof; el = el.parentElement) { if (ev.propagationHasBeenStopped) { return; } this.matchEventAgainstDestinations(el, ev); } }; EventDelegator.prototype.matchEventAgainstDestinations = function (el, ev) { for (var i = 0, n = this.destinations.length; i < n; i++) { var dest = this.destinations[i]; if (!dest.scopeChecker.isStrictlyInRootScope(el)) { continue; } if (matchesSelector(el, dest.selector)) { this.mutateEventCurrentTarget(ev, el); dest.subject._n(ev); } } }; EventDelegator.prototype.capture = function (ev) { for (var i = 0, n = this.destinations.length; i < n; i++) { var dest = this.destinations[i]; if (matchesSelector(ev.target, dest.selector)) { dest.subject._n(ev); } } }; EventDelegator.prototype.addDestination = function (subject, namespace) { var scope = utils_1.getScope(namespace); var selector = utils_1.getSelectors(namespace); var scopeChecker = new ScopeChecker_1.ScopeChecker(scope, this.isolateModule); this.destinations.push({ subject: subject, scopeChecker: scopeChecker, selector: selector }); }; EventDelegator.prototype.patchEvent = function (event) { var pEvent = event; pEvent.propagationHasBeenStopped = false; var oldStopPropagation = pEvent.stopPropagation; pEvent.stopPropagation = function stopPropagation() { oldStopPropagation.call(this); this.propagationHasBeenStopped = true; }; return pEvent; }; EventDelegator.prototype.mutateEventCurrentTarget = function (event, currentTargetElement) { try { Object.defineProperty(event, "currentTarget", { value: currentTargetElement, configurable: true }); } catch (err) { console.log("please use event.ownerTarget"); } event.ownerTarget = currentTargetElement; }; EventDelegator.prototype.updateTopElement = function (newTopElement) { this.topElement.removeEventListener(this.eventType, this.domListener, this.useCapture); newTopElement.addEventListener(this.eventType, this.domListener, this.useCapture); this.topElement = newTopElement; }; return EventDelegator; }(); exports.EventDelegator = EventDelegator; },{"./ScopeChecker":4,"./utils":17,"matches-selector":39}],4:[function(require,module,exports){ "use strict"; var ScopeChecker = function () { function ScopeChecker(scope, isolateModule) { this.scope = scope; this.isolateModule = isolateModule; } ScopeChecker.prototype.isStrictlyInRootScope = function (leaf) { for (var el = leaf; el; el = el.parentElement) { var scope = this.isolateModule.isIsolatedElement(el); if (scope && scope !== this.scope) { return false; } if (scope) { return true; } } return true; }; return ScopeChecker; }(); exports.ScopeChecker = ScopeChecker; },{}],5:[function(require,module,exports){ "use strict"; var hyperscript_1 = require('./hyperscript'); var classNameFromVNode_1 = require('snabbdom-selector/lib/classNameFromVNode'); var selectorParser_1 = require('snabbdom-selector/lib/selectorParser'); var VNodeWrapper = function () { function VNodeWrapper(rootElement) { this.rootElement = rootElement; } VNodeWrapper.prototype.call = function (vnode) { var _a = selectorParser_1.default(vnode.sel), selectorTagName = _a.tagName, selectorId = _a.id; var vNodeClassName = classNameFromVNode_1.default(vnode); var vNodeData = vnode.data || {}; var vNodeDataProps = vNodeData.props || {}; var _b = vNodeDataProps.id, vNodeId = _b === void 0 ? selectorId : _b; var isVNodeAndRootElementIdentical = vNodeId.toUpperCase() === this.rootElement.id.toUpperCase() && selectorTagName.toUpperCase() === this.rootElement.tagName.toUpperCase() && vNodeClassName.toUpperCase() === this.rootElement.className.toUpperCase(); if (isVNodeAndRootElementIdentical) { return vnode; } var _c = this.rootElement, tagName = _c.tagName, id = _c.id, className = _c.className; var elementId = id ? "#" + id : ""; var elementClassName = className ? "." + className.split(" ").join(".") : ""; return hyperscript_1.default("" + tagName + elementId + elementClassName, {}, [vnode]); }; return VNodeWrapper; }(); exports.VNodeWrapper = VNodeWrapper; },{"./hyperscript":8,"snabbdom-selector/lib/classNameFromVNode":40,"snabbdom-selector/lib/selectorParser":41}],6:[function(require,module,exports){ (function (global){ "use strict"; var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null); function fromEvent(element, eventName, useCapture) { if (useCapture === void 0) { useCapture = false; } return xstream_1.Stream.create({ element: element, next: null, start: function start(listener) { this.next = function next(event) { listener.next(event); }; this.element.addEventListener(eventName, this.next, useCapture); }, stop: function stop() { this.element.removeEventListener(eventName, this.next, useCapture); } }); } exports.fromEvent = fromEvent; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],7:[function(require,module,exports){ "use strict"; var hyperscript_1 = require('./hyperscript'); function isValidString(param) { return typeof param === 'string' && param.length > 0; } function isSelector(param) { return isValidString(param) && (param[0] === '.' || param[0] === '#'); } function createTagFunction(tagName) { return function hyperscript(first, b, c) { if (isSelector(first)) { if (!!b && !!c) { return hyperscript_1.default(tagName + first, b, c); } else if (!!b) { return hyperscript_1.default(tagName + first, b); } else { return hyperscript_1.default(tagName + first, {}); } } else if (!!b) { return hyperscript_1.default(tagName, first, b); } else if (!!first) { return hyperscript_1.default(tagName, first); } else { return hyperscript_1.default(tagName, {}); } }; } var SVG_TAG_NAMES = ['a', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'animateTransform', 'circle', 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotlight', 'feTile', 'feTurbulence', 'filter', 'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph', 'mpath', 'path', 'pattern', 'polygon', 'polyling', 'radialGradient', 'rect', 'script', 'set', 'stop', 'style', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref', 'tspan', 'use', 'view', 'vkern']; var svg = createTagFunction('svg'); SVG_TAG_NAMES.forEach(function (tag) { svg[tag] = createTagFunction(tag); }); var TAG_NAMES = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'meta', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'p', 'param', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'u', 'ul', 'video', 'progress']; var exported = { SVG_TAG_NAMES: SVG_TAG_NAMES, TAG_NAMES: TAG_NAMES, svg: svg, isSelector: isSelector, createTagFunction: createTagFunction }; TAG_NAMES.forEach(function (n) { exported[n] = createTagFunction(n); }); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exported; },{"./hyperscript":8}],8:[function(require,module,exports){ "use strict"; var is = require('snabbdom/is'); var vnode = require('snabbdom/vnode'); function isGenericStream(x) { return !Array.isArray(x) && typeof x.map === "function"; } function mutateStreamWithNS(vNode) { addNS(vNode.data, vNode.children); return vNode; } function addNS(data, children) { data.ns = "http://www.w3.org/2000/svg"; if (typeof children !== "undefined" && is.array(children)) { for (var i = 0; i < children.length; ++i) { if (isGenericStream(children[i])) { children[i] = children[i].map(mutateStreamWithNS); } else { addNS(children[i].data, children[i].children); } } } } function h(sel, b, c) { var data = {}; var children; var text; var i; if (arguments.length === 3) { data = b; if (is.array(c)) { children = c; } else if (is.primitive(c)) { text = c; } } else if (arguments.length === 2) { if (is.array(b)) { children = b; } else if (is.primitive(b)) { text = b; } else { data = b; } } if (is.array(children)) { children = children.filter(function (x) { return x; }); for (i = 0; i < children.length; ++i) { if (is.primitive(children[i])) { children[i] = vnode(undefined, undefined, undefined, children[i]); } } } if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') { addNS(data, children); } return vnode(sel, data, children, text, undefined); } ; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = h; },{"snabbdom/is":51,"snabbdom/vnode":60}],9:[function(require,module,exports){ // import * as modules from './modules' // export {modules} "use strict"; var thunk = require('snabbdom/thunk'); exports.thunk = thunk; var hyperscript_1 = require('./hyperscript'); exports.h = hyperscript_1.default; var hyperscript_helpers_1 = require('./hyperscript-helpers'); var a = hyperscript_helpers_1.default.a, abbr = hyperscript_helpers_1.default.abbr, address = hyperscript_helpers_1.default.address, area = hyperscript_helpers_1.default.area, article = hyperscript_helpers_1.default.article, aside = hyperscript_helpers_1.default.aside, audio = hyperscript_helpers_1.default.audio, b = hyperscript_helpers_1.default.b, base = hyperscript_helpers_1.default.base, bdi = hyperscript_helpers_1.default.bdi, bdo = hyperscript_helpers_1.default.bdo, blockquote = hyperscript_helpers_1.default.blockquote, body = hyperscript_helpers_1.default.body, br = hyperscript_helpers_1.default.br, button = hyperscript_helpers_1.default.button, canvas = hyperscript_helpers_1.default.canvas, caption = hyperscript_helpers_1.default.caption, cite = hyperscript_helpers_1.default.cite, code = hyperscript_helpers_1.default.code, col = hyperscript_helpers_1.default.col, colgroup = hyperscript_helpers_1.default.colgroup, dd = hyperscript_helpers_1.default.dd, del = hyperscript_helpers_1.default.del, dfn = hyperscript_helpers_1.default.dfn, dir = hyperscript_helpers_1.default.dir, div = hyperscript_helpers_1.default.div, dl = hyperscript_helpers_1.default.dl, dt = hyperscript_helpers_1.default.dt, em = hyperscript_helpers_1.default.em, embed = hyperscript_helpers_1.default.embed, fieldset = hyperscript_helpers_1.default.fieldset, figcaption = hyperscript_helpers_1.default.figcaption, figure = hyperscript_helpers_1.default.figure, footer = hyperscript_helpers_1.default.footer, form = hyperscript_helpers_1.default.form, h1 = hyperscript_helpers_1.default.h1, h2 = hyperscript_helpers_1.default.h2, h3 = hyperscript_helpers_1.default.h3, h4 = hyperscript_helpers_1.default.h4, h5 = hyperscript_helpers_1.default.h5, h6 = hyperscript_helpers_1.default.h6, head = hyperscript_helpers_1.default.head, header = hyperscript_helpers_1.default.header, hgroup = hyperscript_helpers_1.default.hgroup, hr = hyperscript_helpers_1.default.hr, html = hyperscript_helpers_1.default.html, i = hyperscript_helpers_1.default.i, iframe = hyperscript_helpers_1.default.iframe, img = hyperscript_helpers_1.default.img, input = hyperscript_helpers_1.default.input, ins = hyperscript_helpers_1.default.ins, kbd = hyperscript_helpers_1.default.kbd, keygen = hyperscript_helpers_1.default.keygen, label = hyperscript_helpers_1.default.label, legend = hyperscript_helpers_1.default.legend, li = hyperscript_helpers_1.default.li, link = hyperscript_helpers_1.default.link, main = hyperscript_helpers_1.default.main, map = hyperscript_helpers_1.default.map, mark = hyperscript_helpers_1.default.mark, menu = hyperscript_helpers_1.default.menu, meta = hyperscript_helpers_1.default.meta, nav = hyperscript_helpers_1.default.nav, noscript = hyperscript_helpers_1.default.noscript, object = hyperscript_helpers_1.default.object, ol = hyperscript_helpers_1.default.ol, optgroup = hyperscript_helpers_1.default.optgroup, option = hyperscript_helpers_1.default.option, p = hyperscript_helpers_1.default.p, param = hyperscript_helpers_1.default.param, pre = hyperscript_helpers_1.default.pre, q = hyperscript_helpers_1.default.q, rp = hyperscript_helpers_1.default.rp, rt = hyperscript_helpers_1.default.rt, ruby = hyperscript_helpers_1.default.ruby, s = hyperscript_helpers_1.default.s, samp = hyperscript_helpers_1.default.samp, script = hyperscript_helpers_1.default.script, section = hyperscript_helpers_1.default.section, select = hyperscript_helpers_1.default.select, small = hyperscript_helpers_1.default.small, source = hyperscript_helpers_1.default.source, span = hyperscript_helpers_1.default.span, strong = hyperscript_helpers_1.default.strong, style = hyperscript_helpers_1.default.style, sub = hyperscript_helpers_1.default.sub, sup = hyperscript_helpers_1.default.sup, svg = hyperscript_helpers_1.default.svg, table = hyperscript_helpers_1.default.table, tbody = hyperscript_helpers_1.default.tbody, td = hyperscript_helpers_1.default.td, textarea = hyperscript_helpers_1.default.textarea, tfoot = hyperscript_helpers_1.default.tfoot, th = hyperscript_helpers_1.default.th, thead = hyperscript_helpers_1.default.thead, title = hyperscript_helpers_1.default.title, tr = hyperscript_helpers_1.default.tr, u = hyperscript_helpers_1.default.u, ul = hyperscript_helpers_1.default.ul, video = hyperscript_helpers_1.default.video; exports.a = a; exports.abbr = abbr; exports.address = address; exports.area = area; exports.article = article; exports.aside = aside; exports.audio = audio; exports.b = b; exports.base = base; exports.bdi = bdi; exports.bdo = bdo; exports.blockquote = blockquote; exports.body = body; exports.br = br; exports.button = button; exports.canvas = canvas; exports.caption = caption; exports.cite = cite; exports.code = code; exports.col = col; exports.colgroup = colgroup; exports.dd = dd; exports.del = del; exports.dfn = dfn; exports.dir = dir; exports.div = div; exports.dl = dl; exports.dt = dt; exports.em = em; exports.embed = embed; exports.fieldset = fieldset; exports.figcaption = figcaption; exports.figure = figure; exports.footer = footer; exports.form = form; exports.h1 = h1; exports.h2 = h2; exports.h3 = h3; exports.h4 = h4; exports.h5 = h5; exports.h6 = h6; exports.head = head; exports.header = header; exports.hgroup = hgroup; exports.hr = hr; exports.html = html; exports.i = i; exports.iframe = iframe; exports.img = img; exports.input = input; exports.ins = ins; exports.kbd = kbd; exports.keygen = keygen; exports.label = label; exports.legend = legend; exports.li = li; exports.link = link; exports.main = main; exports.map = map; exports.mark = mark; exports.menu = menu; exports.meta = meta; exports.nav = nav; exports.noscript = noscript; exports.object = object; exports.ol = ol; exports.optgroup = optgroup; exports.option = option; exports.p = p; exports.param = param; exports.pre = pre; exports.q = q; exports.rp = rp; exports.rt = rt; exports.ruby = ruby; exports.s = s; exports.samp = samp; exports.script = script; exports.section = section; exports.select = select; exports.small = small; exports.source = source; exports.span = span; exports.strong = strong; exports.style = style; exports.sub = sub; exports.sup = sup; exports.svg = svg; exports.table = table; exports.tbody = tbody; exports.td = td; exports.textarea = textarea; exports.tfoot = tfoot; exports.th = th; exports.thead = thead; exports.title = title; exports.tr = tr; exports.u = u; exports.ul = ul; exports.video = video; var makeDOMDriver_1 = require('./makeDOMDriver'); exports.makeDOMDriver = makeDOMDriver_1.makeDOMDriver; var mockDOMSource_1 = require('./mockDOMSource'); exports.mockDOMSource = mockDOMSource_1.mockDOMSource; var makeHTMLDriver_1 = require('./makeHTMLDriver'); exports.makeHTMLDriver = makeHTMLDriver_1.makeHTMLDriver; },{"./hyperscript":8,"./hyperscript-helpers":7,"./makeDOMDriver":12,"./makeHTMLDriver":13,"./mockDOMSource":14,"snabbdom/thunk":59}],10:[function(require,module,exports){ "use strict"; var utils_1 = require('./utils'); function isolateSource(source, scope) { return source.select(utils_1.SCOPE_PREFIX + scope); } exports.isolateSource = isolateSource; function isolateSink(sink, scope) { return sink.map(function (vTree) { vTree.data.isolate = utils_1.SCOPE_PREFIX + scope; return vTree; }); } exports.isolateSink = isolateSink; },{"./utils":17}],11:[function(require,module,exports){ "use strict"; var IsolateModule = function () { function IsolateModule(isolatedElements) { this.isolatedElements = isolatedElements; this.eventDelegators = new Map(); } IsolateModule.prototype.setScope = function (elm, scope) { this.isolatedElements.set(scope, elm); }; IsolateModule.prototype.removeScope = function (scope) { this.isolatedElements.delete(scope); }; IsolateModule.prototype.getIsolatedElement = function (scope) { return this.isolatedElements.get(scope); }; IsolateModule.prototype.isIsolatedElement = function (elm) { var elements = Array.from(this.isolatedElements.entries()); for (var i = 0; i < elements.length; ++i) { if (elm === elements[i][1]) { return elements[i][0]; } } return false; }; IsolateModule.prototype.addEventDelegator = function (scope, eventDelegator) { var delegators = this.eventDelegators.get(scope); delegators[delegators.length] = eventDelegator; }; IsolateModule.prototype.reset = function () { this.isolatedElements.clear(); }; IsolateModule.prototype.createModule = function () { var self = this; return { create: function create(oldVNode, vNode) { var _a = oldVNode.data, oldData = _a === void 0 ? {} : _a; var elm = vNode.elm, _b = vNode.data, data = _b === void 0 ? {} : _b; var oldIsolate = oldData.isolate || ""; var isolate = data.isolate || ""; if (isolate) { if (oldIsolate) { self.removeScope(oldIsolate); } self.setScope(elm, isolate); var delegators = self.eventDelegators.get(isolate); if (delegators) { for (var i = 0, len = delegators.length; i < len; ++i) { delegators[i].updateTopElement(elm); } } else if (delegators === void 0) { self.eventDelegators.set(isolate, []); } } if (oldIsolate && !isolate) { self.removeScope(isolate); } }, update: function update(oldVNode, vNode) { var _a = oldVNode.data, oldData = _a === void 0 ? {} : _a; var elm = vNode.elm, _b = vNode.data, data = _b === void 0 ? {} : _b; var oldIsolate = oldData.isolate || ""; var isolate = data.isolate || ""; if (isolate) { if (oldIsolate) { self.removeScope(oldIsolate); } self.setScope(elm, isolate); } if (oldIsolate && !isolate) { self.removeScope(isolate); } }, remove: function remove(_a, cb) { var _b = _a.data, data = _b === void 0 ? {} : _b; var scope = data.isolate; if (scope) { self.removeScope(scope); if (self.eventDelegators.get(scope)) { self.eventDelegators.set(scope, []); } } cb(); }, destroy: function destroy(_a) { var _b = _a.data, data = _b === void 0 ? {} : _b; var scope = data.isolate; if (scope) { self.removeScope(scope); if (self.eventDelegators.get(scope)) { self.eventDelegators.set(scope, []); } } } }; }; return IsolateModule; }(); exports.IsolateModule = IsolateModule; },{}],12:[function(require,module,exports){ (function (global){ "use strict"; var snabbdom_1 = require('snabbdom'); var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null); var concat_1 = require('xstream/extra/concat'); var DOMSource_1 = require('./DOMSource'); var VNodeWrapper_1 = require('./VNodeWrapper'); var utils_1 = require('./utils'); var modules_1 = require('./modules'); var isolateModule_1 = require('./isolateModule'); var transposition_1 = require('./transposition'); var xstream_adapter_1 = require('@cycle/xstream-adapter'); function makeDOMDriverInputGuard(modules) { if (!Array.isArray(modules)) { throw new Error("Optional modules option must be " + "an array for snabbdom modules"); } } function domDriverInputGuard(view$) { if (!view$ || typeof view$.addListener !== "function" || typeof view$.fold !== "function") { throw new Error("The DOM driver function expects as input a Stream of " + "virtual DOM elements"); } } function makeDOMDriver(container, options) { if (!options) { options = {}; } var transposition = options.transposition || false; var modules = options.modules || modules_1.default; var isolateModule = new isolateModule_1.IsolateModule(new Map()); var patch = snabbdom_1.init([isolateModule.createModule()].concat(modules)); var rootElement = utils_1.getElement(container); var vnodeWrapper = new VNodeWrapper_1.VNodeWrapper(rootElement); var delegators = new Map(); makeDOMDriverInputGuard(modules); function DOMDriver(vnode$, runStreamAdapter) { domDriverInputGuard(vnode$); var transposeVNode = transposition_1.makeTransposeVNode(runStreamAdapter); var preprocessedVNode$ = transposition ? vnode$.map(transposeVNode).flatten() : vnode$; var rootElement$ = preprocessedVNode$.map(function (vnode) { return vnodeWrapper.call(vnode); }).fold(patch, rootElement).drop(1).map(function unwrapElementFromVNode(vnode) { return vnode.elm; }).startWith(rootElement).compose(function (stream) { return concat_1.default(stream, xstream_1.default.never()); }) // don't complete this stream .remember(); /* tslint:disable:no-empty */ rootElement$.addListener({ next: function next() {}, error: function error() {}, complete: function complete() {} }); /* tslint:enable:no-empty */ return new DOMSource_1.DOMSource(rootElement$, runStreamAdapter, [], isolateModule, delegators); } ; DOMDriver.streamAdapter = xstream_adapter_1.default; return DOMDriver; } exports.makeDOMDriver = makeDOMDriver; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./DOMSource":1,"./VNodeWrapper":5,"./isolateModule":11,"./modules":15,"./transposition":16,"./utils":17,"@cycle/xstream-adapter":18,"snabbdom":58,"xstream/extra/concat":62}],13:[function(require,module,exports){ (function (global){ "use strict"; var xstream_adapter_1 = require('@cycle/xstream-adapter'); var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null); var transposition_1 = require('./transposition'); var toHTML = require('snabbdom-to-html'); var HTMLSource = function () { function HTMLSource(vnode$, runStreamAdapter) { this.runStreamAdapter = runStreamAdapter; this._html$ = vnode$.last().map(toHTML); this._empty$ = runStreamAdapter.adapt(xstream_1.default.empty(), xstream_adapter_1.default.streamSubscribe); } Object.defineProperty(HTMLSource.prototype, "elements", { get: function get() { return this.runStreamAdapter.adapt(this._html$, xstream_adapter_1.default.streamSubscribe); }, enumerable: true, configurable: true }); HTMLSource.prototype.select = function () { return new HTMLSource(xstream_1.default.empty(), this.runStreamAdapter); }; HTMLSource.prototype.events = function () { return this._empty$; }; return HTMLSource; }(); exports.HTMLSource = HTMLSource; function makeHTMLDriver(options) { if (!options) { options = {}; } var transposition = options.transposition || false; function htmlDriver(vnode$, runStreamAdapter) { var transposeVNode = transposition_1.makeTransposeVNode(runStreamAdapter); var preprocessedVNode$ = transposition ? vnode$.map(transposeVNode).flatten() : vnode$; return new HTMLSource(preprocessedVNode$, runStreamAdapter); } ; htmlDriver.streamAdapter = xstream_adapter_1.default; return htmlDriver; } exports.makeHTMLDriver = makeHTMLDriver; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./transposition":16,"@cycle/xstream-adapter":18,"snabbdom-to-html":43}],14:[function(require,module,exports){ (function (global){ "use strict"; var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null); var MockedDOMSource = function () { function MockedDOMSource(_mockConfig) { this._mockConfig = _mockConfig; if (_mockConfig['elements']) { this.elements = _mockConfig['elements']; } else { this.elements = xstream_1.default.empty(); } } MockedDOMSource.prototype.events = function (eventType) { var mockConfig = this._mockConfig; var keys = Object.keys(mockConfig); var keysLen = keys.length; for (var i = 0; i < keysLen; i++) { var key = keys[i]; if (key === eventType) { return mockConfig[key]; } } return xstream_1.default.empty(); }; MockedDOMSource.prototype.select = function (selector) { var mockConfig = this._mockConfig; var keys = Object.keys(mockConfig); var keysLen = keys.length; for (var i = 0; i < keysLen; i++) { var key = keys[i]; if (key === selector) { return new MockedDOMSource(mockConfig[key]); } } return new MockedDOMSource({}); }; return MockedDOMSource; }(); exports.MockedDOMSource = MockedDOMSource; function mockDOMSource(mockConfig) { return new MockedDOMSource(mockConfig); } exports.mockDOMSource = mockDOMSource; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],15:[function(require,module,exports){ "use strict"; var ClassModule = require('snabbdom/modules/class'); exports.ClassModule = ClassModule; var PropsModule = require('snabbdom/modules/props'); exports.PropsModule = PropsModule; var AttrsModule = require('snabbdom/modules/attributes'); exports.AttrsModule = AttrsModule; var EventsModule = require('snabbdom/modules/eventlisteners'); exports.EventsModule = EventsModule; var StyleModule = require('snabbdom/modules/style'); exports.StyleModule = StyleModule; var HeroModule = require('snabbdom/modules/hero'); exports.HeroModule = HeroModule; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = [StyleModule, ClassModule, PropsModule, AttrsModule]; },{"snabbdom/modules/attributes":52,"snabbdom/modules/class":53,"snabbdom/modules/eventlisteners":54,"snabbdom/modules/hero":55,"snabbdom/modules/props":56,"snabbdom/modules/style":57}],16:[function(require,module,exports){ (function (global){ "use strict"; 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 xstream_adapter_1 = require('@cycle/xstream-adapter'); var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null); function createVTree(vnode, children) { return { sel: vnode.sel, data: vnode.data, text: vnode.text, elm: vnode.elm, key: vnode.key, children: children }; } function makeTransposeVNode(runStreamAdapter) { return function transposeVNode(vnode) { if (!vnode) { return null; } else if (vnode && _typeof(vnode.data) === "object" && vnode.data.static) { return xstream_1.default.of(vnode); } else if (runStreamAdapter.isValidStream(vnode)) { var xsStream = xstream_adapter_1.default.adapt(vnode, runStreamAdapter.streamSubscribe); return xsStream.map(transposeVNode).flatten(); } else if ((typeof vnode === 'undefined' ? 'undefined' : _typeof(vnode)) === "object") { if (!vnode.children || vnode.children.length === 0) { return xstream_1.default.of(vnode); } var vnodeChildren = vnode.children.map(transposeVNode).filter(function (x) { return x !== null; }); return vnodeChildren.length === 0 ? xstream_1.default.of(createVTree(vnode, vnodeChildren)) : xstream_1.default.combine.apply(xstream_1.default, [function () { var children = []; for (var _i = 0; _i < arguments.length; _i++) { children[_i - 0] = arguments[_i]; } return createVTree(vnode, children); }].concat(vnodeChildren)); } else { throw new Error("Unhandled vTree Value"); } }; } exports.makeTransposeVNode = makeTransposeVNode; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"@cycle/xstream-adapter":18}],17:[function(require,module,exports){ "use strict"; 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; }; function isElement(obj) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? obj instanceof HTMLElement || obj instanceof DocumentFragment : obj && (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" && obj !== null && (obj.nodeType === 1 || obj.nodeType === 11) && typeof obj.nodeName === "string"; } exports.SCOPE_PREFIX = "$$CYCLEDOM$$-"; function getElement(selectors) { var domElement = typeof selectors === "string" ? document.querySelector(selectors) : selectors; if (typeof selectors === "string" && domElement === null) { throw new Error("Cannot render into unknown element `" + selectors + "`"); } else if (!isElement(domElement)) { throw new Error("Given container is not a DOM element neither a " + "selector string."); } return domElement; } exports.getElement = getElement; function getScope(namespace) { return namespace.filter(function (c) { return c.indexOf(exports.SCOPE_PREFIX) > -1; }).slice(-1) // only need the latest, most specific, isolated boundary .join(""); } exports.getScope = getScope; function getSelectors(namespace) { return namespace.filter(function (c) { return c.indexOf(exports.SCOPE_PREFIX) === -1; }).join(" "); } exports.getSelectors = getSelectors; },{}],18:[function(require,module,exports){ "use strict"; var xstream_1 = require('xstream'); function logToConsoleError(err) { var target = err.stack || err; if (console && console.error) { console.error(target); } else if (console && console.log) { console.log(target); } } var XStreamAdapter = { adapt: function (originStream, originStreamSubscribe) { if (XStreamAdapter.isValidStream(originStream)) { return originStream; } ; var dispose = null; return xstream_1.default.create({ start: function (out) { var observer = { next: function (value) { return out.shamefullySendNext(value); }, error: function (err) { return out.shamefullySendError(err); }, complete: function () { return out.shamefullySendComplete(); }, }; dispose = originStreamSubscribe(originStream, observer); }, stop: function () { if (typeof dispose === 'function') { dispose(); } } }); }, dispose: function (sinks, sinkProxies, sources) { Object.keys(sources).forEach(function (k) { if (typeof sources[k].dispose === 'function') { sources[k].dispose(); } }); Object.keys(sinks).forEach(function (k) { sinks[k].removeListener(sinkProxies[k].stream); }); }, makeHoldSubject: function () { var stream = xstream_1.default.createWithMemory(); var observer = { next: function (x) { stream.shamefullySendNext(x); }, error: function (err) { logToConsoleError(err); stream.shamefullySendError(err); }, complete: function () { stream.shamefullySendComplete(); } }; return { observer: observer, stream: stream }; }, isValidStream: function (stream) { return (typeof stream.addListener === 'function' && typeof stream.imitate === 'function'); }, streamSubscribe: function (stream, observer) { stream.addListener(observer); return function () { return stream.removeListener(observer); }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = XStreamAdapter; },{"xstream":undefined}],19:[function(require,module,exports){ /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com> * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ module.exports = (function split(undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function(str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return nativeSplit.call(str, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function() { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undef) { match[i] = undef; } } }); } if (match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === str.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; return self; })(); },{}],20:[function(require,module,exports){ /** * lodash 3.1.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArguments = require('lodash.isarguments'), isArray = require('lodash.isarray'); /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * The base implementation of `_.flatten` with added support for restricting * flattening and specifying the start index. * * @private * @param {Array} array The array to flatten. * @param {boolean} [isDeep] Specify a deep flatten. * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, isDeep, isStrict, result) { result || (result = []); var index = -1, length = array.length; while (++index < length) { var value = array[index]; if (isObjectLike(value) && isArrayLike(value) && (isStrict || isArray(value) || isArguments(value))) { if (isDeep) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, isDeep, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = baseFlatten; },{"lodash.isarguments":32,"lodash.isarray":33}],21:[function(require,module,exports){ /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * Creates a base function for methods like `_.forIn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = baseFor; },{}],22:[function(require,module,exports){ /** * lodash 3.1.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * The base implementation of `_.indexOf` without support for binary searches. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return indexOfNaN(array, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * Gets the index at which the first occurrence of `NaN` is found in `array`. * If `fromRight` is provided elements of `array` are iterated from right to left. * * @private * @param {Array} array The array to search. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched `NaN`, else `-1`. */ function indexOfNaN(array, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 0 : -1); while ((fromRight ? index-- : ++index < length)) { var other = array[index]; if (other !== other) { return index; } } return -1; } module.exports = baseIndexOf; },{}],23:[function(require,module,exports){ /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseIndexOf = require('lodash._baseindexof'), cacheIndexOf = require('lodash._cacheindexof'), createCache = require('lodash._createcache'); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of `_.uniq` without support for callback shorthands * and `this` binding. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The function invoked per iteration. * @returns {Array} Returns the new duplicate-value-free array. */ function baseUniq(array, iteratee) { var index = -1, indexOf = baseIndexOf, length = array.length, isCommon = true, isLarge = isCommon && length >= LARGE_ARRAY_SIZE, seen = isLarge ? createCache() : null, result = []; if (seen) { indexOf = cacheIndexOf; isCommon = false; } else { isLarge = false; seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value, index, array) : value; if (isCommon && value === value) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (indexOf(seen, computed, 0) < 0) { if (iteratee || isLarge) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseUniq; },{"lodash._baseindexof":22,"lodash._cacheindexof":25,"lodash._createcache":26}],24:[function(require,module,exports){ /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = bindCallback; },{}],25:[function(require,module,exports){ /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Checks if `value` is in `cache` mimicking the return signature of * `_.indexOf` by returning `0` if the value is found, else `-1`. * * @private * @param {Object} cache The cache to search. * @param {*} value The value to search for. * @returns {number} Returns `0` if `value` is found, else `-1`. */ function cacheIndexOf(cache, value) { var data = cache.data, result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; return result ? 0 : -1; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = cacheIndexOf; },{}],26:[function(require,module,exports){ (function (global){ /** * lodash 3.1.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = require('lodash._getnative'); /** Native method references. */ var Set = getNative(global, 'Set'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeCreate = getNative(Object, 'create'); /** * * Creates a cache object to store unique values. * * @private * @param {Array} [values] The values to cache. */ function SetCache(values) { var length = values ? values.length : 0; this.data = { 'hash': nativeCreate(null), 'set': new Set }; while (length--) { this.push(values[length]); } } /** * Adds `value` to the cache. * * @private * @name push * @memberOf SetCache * @param {*} value The value to cache. */ function cachePush(value) { var data = this.data; if (typeof value == 'string' || isObject(value)) { data.set.add(value); } else { data.hash[value] = true; } } /** * Creates a `Set` cache object to optimize linear searches of large arrays. * * @private * @param {Array} [values] The values to cache. * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. */ function createCache(values) { return (nativeCreate && Set) ? new SetCache(values) : null; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } // Add functions to the `Set` cache. SetCache.prototype.push = cachePush; module.exports = createCache; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"lodash._getnative":27}],27:[function(require,module,exports){ /** * lodash 3.9.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } module.exports = getNative; },{}],28:[function(require,module,exports){ (function (global){ /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** Used to determine if values are of the language type `Object`. */ var objectTypes = { 'function': true, 'object': true }; /** Detect free variable `exports`. */ var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : undefined; /** Detect free variable `module`. */ var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : undefined; /** Detect free variable `global` from Node.js. */ var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global); /** Detect free variable `self`. */ var freeSelf = checkGlobal(objectTypes[typeof self] && self); /** Detect free variable `window`. */ var freeWindow = checkGlobal(objectTypes[typeof window] && window); /** Detect `this` as the global object. */ var thisGlobal = checkGlobal(objectTypes[typeof this] && this); /** * Used as a reference to the global object. * * The `this` value is used if it's the global object to avoid Greasemonkey's * restricted `window` object, otherwise the `window` object is used. */ var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); /** * Checks if `value` is a global object. * * @private * @param {*} value The value to check. * @returns {null|Object} Returns `value` if it's a global object, else `null`. */ function checkGlobal(value) { return (value && value.Object === Object) ? value : null; } module.exports = root; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],29:[function(require,module,exports){ /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var root = require('lodash._root'); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; /** Used to compose unicode character classes. */ var rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0'; /** Used to compose unicode capture groups. */ var rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']'; /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to map latin-1 supplementary letters to basic latin letters. */ var deburredLetters = { '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss' }; /** * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ function deburrLetter(letter) { return deburredLetters[letter]; } /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = Symbol ? symbolProto.toString : undefined; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (value == null) { return ''; } if (isSymbol(value)) { return Symbol ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } module.exports = deburr; },{"lodash._root":28}],30:[function(require,module,exports){ /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var root = require('lodash._root'); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to match HTML entities and HTML characters. */ var reUnescapedHtml = /[&<>"'`]/g, reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '`': '&#96;' }; /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(chr) { return htmlEscapes[chr]; } /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = Symbol ? symbolProto.toString : undefined; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (value == null) { return ''; } if (isSymbol(value)) { return Symbol ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to * their corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * Backticks are escaped because in IE < 9, they can break out of * attribute values or HTML comments. See [#59](https://html5sec.org/#59), * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/) * for more details. * * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) * to reduce XSS vectors. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } module.exports = escape; },{"lodash._root":28}],31:[function(require,module,exports){ /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseFor = require('lodash._basefor'), bindCallback = require('lodash._bindcallback'), keys = require('lodash.keys'); /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * Creates a function for `_.forOwn` or `_.forOwnRight`. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new each function. */ function createForOwn(objectFunc) { return function(object, iteratee, thisArg) { if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee); }; } /** * Iterates over own enumerable properties of an object invoking `iteratee` * for each property. The `iteratee` is bound to `thisArg` and invoked with * three arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'a' and 'b' (iteration order is not guaranteed) */ var forOwn = createForOwn(baseForOwn); module.exports = forOwn; },{"lodash._basefor":21,"lodash._bindcallback":24,"lodash.keys":35}],32:[function(require,module,exports){ /** * lodash 3.0.8 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(getLength(value)) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isArguments; },{}],33:[function(require,module,exports){ /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var arrayTag = '[object Array]', funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } module.exports = isArray; },{}],34:[function(require,module,exports){ /** * lodash 3.1.1 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var deburr = require('lodash.deburr'), words = require('lodash.words'); /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string)), callback, ''); }; } /** * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__foo_bar__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); module.exports = kebabCase; },{"lodash.deburr":29,"lodash.words":38}],35:[function(require,module,exports){ /** * lodash 3.1.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = require('lodash._getnative'), isArguments = require('lodash.isarguments'), isArray = require('lodash.isarray'); /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keys; },{"lodash._getnative":27,"lodash.isarguments":32,"lodash.isarray":33}],36:[function(require,module,exports){ /** * lodash 3.6.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; },{}],37:[function(require,module,exports){ /** * lodash 3.1.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseFlatten = require('lodash._baseflatten'), baseUniq = require('lodash._baseuniq'), restParam = require('lodash.restparam'); /** * Creates an array of unique values, in order, of the provided arrays using * `SameValueZero` for equality comparisons. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([1, 2], [4, 2], [2, 1]); * // => [1, 2, 4] */ var union = restParam(function(arrays) { return baseUniq(baseFlatten(arrays, false, true)); }); module.exports = union; },{"lodash._baseflatten":20,"lodash._baseuniq":23,"lodash.restparam":36}],38:[function(require,module,exports){ /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var root = require('lodash._root'); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsQuoteRange = '\\u2018\\u2019\\u201c\\u201d', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsQuoteRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq; /** Used to match non-compound words composed of alphanumeric characters. */ var reBasicWord = /[a-zA-Z0-9]+/g; /** Used to match complex or compound words. */ var reComplexWord = RegExp([ rsUpper + '?' + rsLower + '+(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsUpperMisc + '+(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', rsUpper + '?' + rsLowerMisc + '+', rsUpper + '+', rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasComplexWord = /[a-z][A-Z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = Symbol ? symbolProto.toString : undefined; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (value == null) { return ''; } if (isSymbol(value)) { return Symbol ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord; } return string.match(pattern) || []; } module.exports = words; },{"lodash._root":28}],39:[function(require,module,exports){ 'use strict'; var proto = Element.prototype; var vendor = proto.matches || proto.matchesSelector || proto.webkitMatchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector; module.exports = match; /** * Match `el` to `selector`. * * @param {Element} el * @param {String} selector * @return {Boolean} * @api public */ function match(el, selector) { if (vendor) return vendor.call(el, selector); var nodes = el.parentNode.querySelectorAll(selector); for (var i = 0; i < nodes.length; i++) { if (nodes[i] == el) return true; } return false; } },{}],40:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNameFromVNode; var _selectorParser2 = require('./selectorParser'); var _selectorParser3 = _interopRequireDefault(_selectorParser2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function classNameFromVNode(vNode) { var _selectorParser = (0, _selectorParser3.default)(vNode.sel); var cn = _selectorParser.className; if (!vNode.data) { return cn; } var _vNode$data = vNode.data; var dataClass = _vNode$data.class; var props = _vNode$data.props; if (dataClass) { var c = Object.keys(vNode.data.class).filter(function (cl) { return vNode.data.class[cl]; }); cn += ' ' + c.join(' '); } if (props && props.className) { cn += ' ' + props.className; } return cn.trim(); } },{"./selectorParser":41}],41:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = selectorParser; var _browserSplit = require('browser-split'); var _browserSplit2 = _interopRequireDefault(_browserSplit); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; var notClassId = /^\.|#/; function selectorParser() { var selector = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var tagName = undefined; var id = ''; var classes = []; var tagParts = (0, _browserSplit2.default)(selector, classIdSplit); if (notClassId.test(tagParts[1]) || selector === '') { tagName = 'div'; } var part = undefined; var type = undefined; var i = undefined; for (i = 0; i < tagParts.length; i++) { part = tagParts[i]; if (!part) { continue; } type = part.charAt(0); if (!tagName) { tagName = part; } else if (type === '.') { classes.push(part.substring(1, part.length)); } else if (type === '#') { id = part.substring(1, part.length); } } return { tagName: tagName, id: id, className: classes.join(' ') }; } },{"browser-split":19}],42:[function(require,module,exports){ // All SVG children elements, not in this list, should self-close module.exports = { // http://www.w3.org/TR/SVG/intro.html#TermContainerElement 'a': true, 'defs': true, 'glyph': true, 'g': true, 'marker': true, 'mask': true, 'missing-glyph': true, 'pattern': true, 'svg': true, 'switch': true, 'symbol': true, // http://www.w3.org/TR/SVG/intro.html#TermDescriptiveElement 'desc': true, 'metadata': true, 'title': true }; },{}],43:[function(require,module,exports){ var init = require('./init'); module.exports = init([require('./modules/attributes'), require('./modules/style')]); },{"./init":44,"./modules/attributes":45,"./modules/style":46}],44:[function(require,module,exports){ var parseSelector = require('./parse-selector'); var VOID_ELEMENTS = require('./void-elements'); var CONTAINER_ELEMENTS = require('./container-elements'); module.exports = function init(modules) { function parse(data) { return modules.reduce(function (arr, fn) { arr.push(fn(data)); return arr; }, []).filter(function (result) { return result !== ''; }); } return function renderToString(vnode) { if (!vnode.sel && vnode.text) { return vnode.text; } vnode.data = vnode.data || {}; // Support thunks if (typeof vnode.sel === 'string' && vnode.sel.slice(0, 5) === 'thunk') { vnode = vnode.data.fn.apply(null, vnode.data.args); } var tagName = parseSelector(vnode.sel).tagName; var attributes = parse(vnode); var svg = vnode.data.ns === 'http://www.w3.org/2000/svg'; var tag = []; // Open tag tag.push('<' + tagName); if (attributes.length) { tag.push(' ' + attributes.join(' ')); } if (svg && CONTAINER_ELEMENTS[tagName] !== true) { tag.push(' /'); } tag.push('>'); // Close tag, if needed if (VOID_ELEMENTS[tagName] !== true && !svg || svg && CONTAINER_ELEMENTS[tagName] === true) { if (vnode.data.props && vnode.data.props.innerHTML) { tag.push(vnode.data.props.innerHTML); } else if (vnode.text) { tag.push(vnode.text); } else if (vnode.children) { vnode.children.forEach(function (child) { tag.push(renderToString(child)); }); } tag.push('</' + tagName + '>'); } return tag.join(''); }; }; },{"./container-elements":42,"./parse-selector":47,"./void-elements":48}],45:[function(require,module,exports){ var forOwn = require('lodash.forown'); var escape = require('lodash.escape'); var union = require('lodash.union'); var parseSelector = require('../parse-selector'); // data.attrs, data.props, data.class module.exports = function attributes(vnode) { var selector = parseSelector(vnode.sel); var parsedClasses = selector.className.split(' '); var attributes = []; var classes = []; var values = {}; if (selector.id) { values.id = selector.id; } setAttributes(vnode.data.props, values); setAttributes(vnode.data.attrs, values); // `attrs` override `props`, not sure if this is good so if (vnode.data.class) { // Omit `className` attribute if `class` is set on vnode values.class = undefined; } forOwn(vnode.data.class, function (value, key) { if (value === true) { classes.push(key); } }); classes = union(classes, values.class, parsedClasses).filter(function (x) { return x !== ''; }); if (classes.length) { values.class = classes.join(' '); } forOwn(values, function (value, key) { attributes.push(value === true ? key : key + '="' + escape(value) + '"'); }); return attributes.length ? attributes.join(' ') : ''; }; function setAttributes(values, target) { forOwn(values, function (value, key) { if (key === 'htmlFor') { target['for'] = value; return; } if (key === 'className') { target['class'] = value.split(' '); return; } if (key === 'innerHTML') { return; } target[key] = value; }); } },{"../parse-selector":47,"lodash.escape":30,"lodash.forown":31,"lodash.union":37}],46:[function(require,module,exports){ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var forOwn = require('lodash.forown'); var escape = require('lodash.escape'); var kebabCase = require('lodash.kebabcase'); // data.style module.exports = function style(vnode) { var styles = []; var style = vnode.data.style || {}; // merge in `delayed` properties if (style.delayed) { _extends(style, style.delayed); } forOwn(style, function (value, key) { // omit hook objects if (typeof value === 'string') { styles.push(kebabCase(key) + ': ' + escape(value)); } }); return styles.length ? 'style="' + styles.join('; ') + '"' : ''; }; },{"lodash.escape":30,"lodash.forown":31,"lodash.kebabcase":34}],47:[function(require,module,exports){ // https://github.com/Matt-Esch/virtual-dom/blob/master/virtual-hyperscript/parse-tag.js var split = require('browser-split'); var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; var notClassId = /^\.|#/; module.exports = function parseSelector(selector, upper) { selector = selector || ''; var tagName; var id = ''; var classes = []; var tagParts = split(selector, classIdSplit); if (notClassId.test(tagParts[1]) || selector === '') { tagName = 'div'; } var part, type, i; for (i = 0; i < tagParts.length; i++) { part = tagParts[i]; if (!part) { continue; } type = part.charAt(0); if (!tagName) { tagName = part; } else if (type === '.') { classes.push(part.substring(1, part.length)); } else if (type === '#') { id = part.substring(1, part.length); } } return { tagName: upper === true ? tagName.toUpperCase() : tagName, id: id, className: classes.join(' ') }; }; },{"browser-split":19}],48:[function(require,module,exports){ // http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements module.exports = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }; },{}],49:[function(require,module,exports){ var VNode = require('./vnode'); var is = require('./is'); function addNS(data, children) { data.ns = 'http://www.w3.org/2000/svg'; if (children !== undefined) { for (var i = 0; i < children.length; ++i) { addNS(children[i].data, children[i].children); } } } module.exports = function h(sel, b, c) { var data = {}, children, text, i; if (arguments.length === 3) { data = b; if (is.array(c)) { children = c; } else if (is.primitive(c)) { text = c; } } else if (arguments.length === 2) { if (is.array(b)) { children = b; } else if (is.primitive(b)) { text = b; } else { data = b; } } if (is.array(children)) { for (i = 0; i < children.length; ++i) { if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]); } } if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') { addNS(data, children); } return VNode(sel, data, children, text, undefined); }; },{"./is":51,"./vnode":60}],50:[function(require,module,exports){ function createElement(tagName){ return document.createElement(tagName); } function createElementNS(namespaceURI, qualifiedName){ return document.createElementNS(namespaceURI, qualifiedName); } function createTextNode(text){ return document.createTextNode(text); } function insertBefore(parentNode, newNode, referenceNode){ parentNode.insertBefore(newNode, referenceNode); } function removeChild(node, child){ node.removeChild(child); } function appendChild(node, child){ node.appendChild(child); } function parentNode(node){ return node.parentElement; } function nextSibling(node){ return node.nextSibling; } function tagName(node){ return node.tagName; } function setTextContent(node, text){ node.textContent = text; } module.exports = { createElement: createElement, createElementNS: createElementNS, createTextNode: createTextNode, appendChild: appendChild, removeChild: removeChild, insertBefore: insertBefore, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent }; },{}],51:[function(require,module,exports){ module.exports = { array: Array.isArray, primitive: function(s) { return typeof s === 'string' || typeof s === 'number'; }, }; },{}],52:[function(require,module,exports){ var booleanAttrs = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "compact", "controls", "declare", "default", "defaultchecked", "defaultmuted", "defaultselected", "defer", "disabled", "draggable", "enabled", "formnovalidate", "hidden", "indeterminate", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "pauseonexit", "readonly", "required", "reversed", "scoped", "seamless", "selected", "sortable", "spellcheck", "translate", "truespeed", "typemustmatch", "visible"]; var booleanAttrsDict = {}; for(var i=0, len = booleanAttrs.length; i < len; i++) { booleanAttrsDict[booleanAttrs[i]] = true; } function updateAttrs(oldVnode, vnode) { var key, cur, old, elm = vnode.elm, oldAttrs = oldVnode.data.attrs || {}, attrs = vnode.data.attrs || {}; // update modified attributes, add new attributes for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { // TODO: add support to namespaced attributes (setAttributeNS) if(!cur && booleanAttrsDict[key]) elm.removeAttribute(key); else elm.setAttribute(key, cur); } } //remove removed attributes // use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value) // the other option is to remove all attributes with value == undefined for (key in oldAttrs) { if (!(key in attrs)) { elm.removeAttribute(key); } } } module.exports = {create: updateAttrs, update: updateAttrs}; },{}],53:[function(require,module,exports){ function updateClass(oldVnode, vnode) { var cur, name, elm = vnode.elm, oldClass = oldVnode.data.class || {}, klass = vnode.data.class || {}; for (name in oldClass) { if (!klass[name]) { elm.classList.remove(name); } } for (name in klass) { cur = klass[name]; if (cur !== oldClass[name]) { elm.classList[cur ? 'add' : 'remove'](name); } } } module.exports = {create: updateClass, update: updateClass}; },{}],54:[function(require,module,exports){ var is = require('../is'); function arrInvoker(arr) { return function() { // Special case when length is two, for performance arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1)); }; } function fnInvoker(o) { return function(ev) { o.fn(ev); }; } function updateEventListeners(oldVnode, vnode) { var name, cur, old, elm = vnode.elm, oldOn = oldVnode.data.on || {}, on = vnode.data.on; if (!on) return; for (name in on) { cur = on[name]; old = oldOn[name]; if (old === undefined) { if (is.array(cur)) { elm.addEventListener(name, arrInvoker(cur)); } else { cur = {fn: cur}; on[name] = cur; elm.addEventListener(name, fnInvoker(cur)); } } else if (is.array(old)) { // Deliberately modify old array since it's captured in closure created with `arrInvoker` old.length = cur.length; for (var i = 0; i < old.length; ++i) old[i] = cur[i]; on[name] = old; } else { old.fn = cur; on[name] = old; } } } module.exports = {create: updateEventListeners, update: updateEventListeners}; },{"../is":51}],55:[function(require,module,exports){ var raf = (typeof window !== 'undefined' && window.requestAnimationFrame) || setTimeout; var nextFrame = function(fn) { raf(function() { raf(fn); }); }; function setNextFrame(obj, prop, val) { nextFrame(function() { obj[prop] = val; }); } function getTextNodeRect(textNode) { var rect; if (document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if (range.getBoundingClientRect) { rect = range.getBoundingClientRect(); } } return rect; } function calcTransformOrigin(isTextNode, textRect, boundingRect) { if (isTextNode) { if (textRect) { //calculate pixels to center of text from left edge of bounding box var relativeCenterX = textRect.left + textRect.width/2 - boundingRect.left; var relativeCenterY = textRect.top + textRect.height/2 - boundingRect.top; return relativeCenterX + 'px ' + relativeCenterY + 'px'; } } return '0 0'; //top left } function getTextDx(oldTextRect, newTextRect) { if (oldTextRect && newTextRect) { return ((oldTextRect.left + oldTextRect.width/2) - (newTextRect.left + newTextRect.width/2)); } return 0; } function getTextDy(oldTextRect, newTextRect) { if (oldTextRect && newTextRect) { return ((oldTextRect.top + oldTextRect.height/2) - (newTextRect.top + newTextRect.height/2)); } return 0; } function isTextElement(elm) { return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3; } var removed, created; function pre(oldVnode, vnode) { removed = {}; created = []; } function create(oldVnode, vnode) { var hero = vnode.data.hero; if (hero && hero.id) { created.push(hero.id); created.push(vnode); } } function destroy(vnode) { var hero = vnode.data.hero; if (hero && hero.id) { var elm = vnode.elm; vnode.isTextNode = isTextElement(elm); //is this a text node? vnode.boundingRect = elm.getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode vnode.textRect = vnode.isTextNode ? getTextNodeRect(elm.childNodes[0]) : null; //save bounding rect of inner text node var computedStyle = window.getComputedStyle(elm, null); //get current styles (includes inherited properties) vnode.savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values removed[hero.id] = vnode; } } function post() { var i, id, newElm, oldVnode, oldElm, hRatio, wRatio, oldRect, newRect, dx, dy, origTransform, origTransition, newStyle, oldStyle, newComputedStyle, isTextNode, newTextRect, oldTextRect; for (i = 0; i < created.length; i += 2) { id = created[i]; newElm = created[i+1].elm; oldVnode = removed[id]; if (oldVnode) { isTextNode = oldVnode.isTextNode && isTextElement(newElm); //Are old & new both text? newStyle = newElm.style; newComputedStyle = window.getComputedStyle(newElm, null); //get full computed style for new element oldElm = oldVnode.elm; oldStyle = oldElm.style; //Overall element bounding boxes newRect = newElm.getBoundingClientRect(); oldRect = oldVnode.boundingRect; //previously saved bounding rect //Text node bounding boxes & distances if (isTextNode) { newTextRect = getTextNodeRect(newElm.childNodes[0]); oldTextRect = oldVnode.textRect; dx = getTextDx(oldTextRect, newTextRect); dy = getTextDy(oldTextRect, newTextRect); } else { //Calculate distances between old & new positions dx = oldRect.left - newRect.left; dy = oldRect.top - newRect.top; } hRatio = newRect.height / (Math.max(oldRect.height, 1)); wRatio = isTextNode ? hRatio : newRect.width / (Math.max(oldRect.width, 1)); //text scales based on hRatio // Animate new element origTransform = newStyle.transform; origTransition = newStyle.transition; if (newComputedStyle.display === 'inline') //inline elements cannot be transformed newStyle.display = 'inline-block'; //this does not appear to have any negative side effects newStyle.transition = origTransition + 'transform 0s'; newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect); newStyle.opacity = '0'; newStyle.transform = origTransform + 'translate('+dx+'px, '+dy+'px) ' + 'scale('+1/wRatio+', '+1/hRatio+')'; setNextFrame(newStyle, 'transition', origTransition); setNextFrame(newStyle, 'transform', origTransform); setNextFrame(newStyle, 'opacity', '1'); // Animate old element for (var key in oldVnode.savedStyle) { //re-apply saved inherited properties if (parseInt(key) != key) { var ms = key.substring(0,2) === 'ms'; var moz = key.substring(0,3) === 'moz'; var webkit = key.substring(0,6) === 'webkit'; if (!ms && !moz && !webkit) //ignore prefixed style properties oldStyle[key] = oldVnode.savedStyle[key]; } } oldStyle.position = 'absolute'; oldStyle.top = oldRect.top + 'px'; //start at existing position oldStyle.left = oldRect.left + 'px'; oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents oldStyle.margin = 0; //Margin on hero element leads to incorrect positioning oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect); oldStyle.transform = ''; oldStyle.opacity = '1'; document.body.appendChild(oldElm); setNextFrame(oldStyle, 'transform', 'translate('+ -dx +'px, '+ -dy +'px) scale('+wRatio+', '+hRatio+')'); //scale must be on far right for translate to be correct setNextFrame(oldStyle, 'opacity', '0'); oldElm.addEventListener('transitionend', function(ev) { if (ev.propertyName === 'transform') document.body.removeChild(ev.target); }); } } removed = created = undefined; } module.exports = {pre: pre, create: create, destroy: destroy, post: post}; },{}],56:[function(require,module,exports){ function updateProps(oldVnode, vnode) { var key, cur, old, elm = vnode.elm, oldProps = oldVnode.data.props || {}, props = vnode.data.props || {}; for (key in oldProps) { if (!props[key]) { delete elm[key]; } } for (key in props) { cur = props[key]; old = oldProps[key]; if (old !== cur && (key !== 'value' || elm[key] !== cur)) { elm[key] = cur; } } } module.exports = {create: updateProps, update: updateProps}; },{}],57:[function(require,module,exports){ var raf = (typeof window !== 'undefined' && window.requestAnimationFrame) || setTimeout; var nextFrame = function(fn) { raf(function() { raf(fn); }); }; function setNextFrame(obj, prop, val) { nextFrame(function() { obj[prop] = val; }); } function updateStyle(oldVnode, vnode) { var cur, name, elm = vnode.elm, oldStyle = oldVnode.data.style || {}, style = vnode.data.style || {}, oldHasDel = 'delayed' in oldStyle; for (name in oldStyle) { if (!style[name]) { elm.style[name] = ''; } } for (name in style) { cur = style[name]; if (name === 'delayed') { for (name in style.delayed) { cur = style.delayed[name]; if (!oldHasDel || cur !== oldStyle.delayed[name]) { setNextFrame(elm.style, name, cur); } } } else if (name !== 'remove' && cur !== oldStyle[name]) { elm.style[name] = cur; } } } function applyDestroyStyle(vnode) { var style, name, elm = vnode.elm, s = vnode.data.style; if (!s || !(style = s.destroy)) return; for (name in style) { elm.style[name] = style[name]; } } function applyRemoveStyle(vnode, rm) { var s = vnode.data.style; if (!s || !s.remove) { rm(); return; } var name, elm = vnode.elm, idx, i = 0, maxDur = 0, compStyle, style = s.remove, amount = 0, applied = []; for (name in style) { applied.push(name); elm.style[name] = style[name]; } compStyle = getComputedStyle(elm); var props = compStyle['transition-property'].split(', '); for (; i < props.length; ++i) { if(applied.indexOf(props[i]) !== -1) amount++; } elm.addEventListener('transitionend', function(ev) { if (ev.target === elm) --amount; if (amount === 0) rm(); }); } module.exports = {create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle}; },{}],58:[function(require,module,exports){ // jshint newcap: false /* global require, module, document, Node */ 'use strict'; var VNode = require('./vnode'); var is = require('./is'); var domApi = require('./htmldomapi.js'); function isUndef(s) { return s === undefined; } function isDef(s) { return s !== undefined; } var emptyNode = VNode('', {}, [], undefined, undefined); function sameVnode(vnode1, vnode2) { return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel; } function createKeyToOldIdx(children, beginIdx, endIdx) { var i, map = {}, key; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) map[key] = i; } return map; } var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post']; function init(modules, api) { var i, j, cbs = {}; if (isUndef(api)) api = domApi; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]); } } function emptyNodeAt(elm) { return VNode(api.tagName(elm).toLowerCase(), {}, [], undefined, elm); } function createRmCb(childElm, listeners) { return function() { if (--listeners === 0) { var parent = api.parentNode(childElm); api.removeChild(parent, childElm); } }; } function createElm(vnode, insertedVnodeQueue) { var i, thunk, data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode); if (isDef(i = data.vnode)) { thunk = vnode; vnode = i; } } var elm, children = vnode.children, sel = vnode.sel; if (isDef(sel)) { // Parse selector var hashIdx = sel.indexOf('#'); var dotIdx = sel.indexOf('.', hashIdx); var hash = hashIdx > 0 ? hashIdx : sel.length; var dot = dotIdx > 0 ? dotIdx : sel.length; var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel; elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? api.createElementNS(i, tag) : api.createElement(tag); if (hash < dot) elm.id = sel.slice(hash + 1, dot); if (dotIdx > 0) elm.className = sel.slice(dot+1).replace(/\./g, ' '); if (is.array(children)) { for (i = 0; i < children.length; ++i) { api.appendChild(elm, createElm(children[i], insertedVnodeQueue)); } } else if (is.primitive(vnode.text)) { api.appendChild(elm, api.createTextNode(vnode.text)); } for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode); i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (i.create) i.create(emptyNode, vnode); if (i.insert) insertedVnodeQueue.push(vnode); } } else { elm = vnode.elm = api.createTextNode(vnode.text); } if (isDef(thunk)) thunk.elm = vnode.elm; return vnode.elm; } function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { api.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before); } } function invokeDestroyHook(vnode) { var i, j, data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode); for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode); if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } if (isDef(i = data.vnode)) invokeDestroyHook(i); } } function removeVnodes(parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var i, listeners, rm, ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.sel)) { invokeDestroyHook(ch); listeners = cbs.remove.length + 1; rm = createRmCb(ch.elm, listeners); for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm); if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) { i(ch, rm); } else { rm(); } } else { // Text node api.removeChild(parentElm, ch.elm); } } } } function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) { var oldStartIdx = 0, newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, elmToMove, before; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); api.insertBefore(parentElm, oldStartVnode.elm, api.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); api.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); idxInOld = oldKeyToIdx[newStartVnode.key]; if (isUndef(idxInOld)) { // New element api.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; api.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } if (oldStartIdx > oldEndIdx) { before = isUndef(newCh[newEndIdx+1]) ? null : newCh[newEndIdx+1].elm; addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode(oldVnode, vnode, insertedVnodeQueue) { var i, hook; if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) { i(oldVnode, vnode); } if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i; if (isDef(i = vnode.data) && isDef(i = i.vnode)) { patchVnode(oldVnode, i, insertedVnodeQueue); vnode.elm = i.elm; return; } var elm = vnode.elm = oldVnode.elm, oldCh = oldVnode.children, ch = vnode.children; if (oldVnode === vnode) return; if (!sameVnode(oldVnode, vnode)) { var parentElm = api.parentNode(oldVnode.elm); elm = createElm(vnode, insertedVnodeQueue); api.insertBefore(parentElm, elm, oldVnode.elm); removeVnodes(parentElm, [oldVnode], 0, 0); return; } if (isDef(vnode.data)) { for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode); i = vnode.data.hook; if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode); } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue); } else if (isDef(ch)) { if (isDef(oldVnode.text)) api.setTextContent(elm, ''); addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { api.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { api.setTextContent(elm, vnode.text); } if (isDef(hook) && isDef(i = hook.postpatch)) { i(oldVnode, vnode); } } return function(oldVnode, vnode) { var i, elm, parent; var insertedVnodeQueue = []; for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i](); if (isUndef(oldVnode.sel)) { oldVnode = emptyNodeAt(oldVnode); } if (sameVnode(oldVnode, vnode)) { patchVnode(oldVnode, vnode, insertedVnodeQueue); } else { elm = oldVnode.elm; parent = api.parentNode(elm); createElm(vnode, insertedVnodeQueue); if (parent !== null) { api.insertBefore(parent, vnode.elm, api.nextSibling(elm)); removeVnodes(parent, [oldVnode], 0, 0); } } for (i = 0; i < insertedVnodeQueue.length; ++i) { insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]); } for (i = 0; i < cbs.post.length; ++i) cbs.post[i](); return vnode; }; } module.exports = {init: init}; },{"./htmldomapi.js":50,"./is":51,"./vnode":60}],59:[function(require,module,exports){ var h = require('./h'); function init(thunk) { var i, cur = thunk.data; cur.vnode = cur.fn.apply(undefined, cur.args); } function prepatch(oldThunk, thunk) { var i, old = oldThunk.data, cur = thunk.data; var oldArgs = old.args, args = cur.args; cur.vnode = old.vnode; if (old.fn !== cur.fn || oldArgs.length !== args.length) { cur.vnode = cur.fn.apply(undefined, args); return; } for (i = 0; i < args.length; ++i) { if (oldArgs[i] !== args[i]) { cur.vnode = cur.fn.apply(undefined, args); return; } } } module.exports = function(name, fn /* args */) { var i, args = []; for (i = 2; i < arguments.length; ++i) { args[i - 2] = arguments[i]; } return h('thunk' + name, { hook: {init: init, prepatch: prepatch}, fn: fn, args: args, }); }; },{"./h":49}],60:[function(require,module,exports){ module.exports = function(sel, data, children, text, elm) { var key = data === undefined ? undefined : data.key; return {sel: sel, data: data, children: children, text: text, elm: elm, key: key}; }; },{}],61:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var empty = {}; function noop() { } function copy(a) { var l = a.length; var b = Array(l); for (var i = 0; i < l; ++i) { b[i] = a[i]; } return b; } exports.emptyListener = { _n: noop, _e: noop, _c: noop, }; // mutates the input function internalizeProducer(producer) { producer._start = function _start(il) { il.next = il._n; il.error = il._e; il.complete = il._c; this.start(il); }; producer._stop = producer.stop; } function invoke(f, args) { switch (args.length) { case 0: return f(); case 1: return f(args[0]); case 2: return f(args[0], args[1]); case 3: return f(args[0], args[1], args[2]); case 4: return f(args[0], args[1], args[2], args[3]); case 5: return f(args[0], args[1], args[2], args[3], args[4]); default: return f.apply(void 0, args); } } function compose2(f1, f2) { return function composedFn(arg) { return f1(f2(arg)); }; } function and(f1, f2) { return function andFn(t) { return f1(t) && f2(t); }; } var CombineListener = (function () { function CombineListener(i, p) { this.i = i; this.p = p; p.ils.push(this); } CombineListener.prototype._n = function (t) { var p = this.p, out = p.out; if (!out) return; if (p.up(t, this.i)) { try { out._n(invoke(p.project, p.vals)); } catch (e) { out._e(e); } } }; CombineListener.prototype._e = function (err) { var out = this.p.out; if (!out) return; out._e(err); }; CombineListener.prototype._c = function () { var p = this.p; if (!p.out) return; if (--p.ac === 0) { p.out._c(); } }; return CombineListener; }()); exports.CombineListener = CombineListener; var CombineProducer = (function () { function CombineProducer(project, streams) { this.project = project; this.streams = streams; this.type = 'combine'; this.out = exports.emptyListener; this.ils = []; var n = this.ac = this.left = streams.length; var vals = this.vals = new Array(n); for (var i = 0; i < n; i++) { vals[i] = empty; } } CombineProducer.prototype.up = function (t, i) { var v = this.vals[i]; var left = !this.left ? 0 : v === empty ? --this.left : this.left; this.vals[i] = t; return left === 0; }; CombineProducer.prototype._start = function (out) { this.out = out; var s = this.streams; var n = s.length; if (n === 0) this.zero(out); else { for (var i = 0; i < n; i++) { s[i]._add(new CombineListener(i, this)); } } }; CombineProducer.prototype._stop = function () { var s = this.streams; var n = this.ac = this.left = s.length; var vals = this.vals = new Array(n); for (var i = 0; i < n; i++) { s[i]._remove(this.ils[i]); vals[i] = empty; } this.out = null; this.ils = []; }; CombineProducer.prototype.zero = function (out) { try { out._n(this.project()); out._c(); } catch (e) { out._e(e); } }; return CombineProducer; }()); exports.CombineProducer = CombineProducer; var FromArrayProducer = (function () { function FromArrayProducer(a) { this.a = a; this.type = 'fromArray'; } FromArrayProducer.prototype._start = function (out) { var a = this.a; for (var i = 0, l = a.length; i < l; i++) { out._n(a[i]); } out._c(); }; FromArrayProducer.prototype._stop = function () { }; return FromArrayProducer; }()); exports.FromArrayProducer = FromArrayProducer; var FromPromiseProducer = (function () { function FromPromiseProducer(p) { this.p = p; this.type = 'fromPromise'; this.on = false; } FromPromiseProducer.prototype._start = function (out) { var prod = this; this.on = true; this.p.then(function (v) { if (prod.on) { out._n(v); out._c(); } }, function (e) { out._e(e); }).then(null, function (err) { setTimeout(function () { throw err; }); }); }; FromPromiseProducer.prototype._stop = function () { this.on = false; }; return FromPromiseProducer; }()); exports.FromPromiseProducer = FromPromiseProducer; var MergeProducer = (function () { function MergeProducer(streams) { this.streams = streams; this.type = 'merge'; this.out = exports.emptyListener; this.ac = streams.length; } MergeProducer.prototype._start = function (out) { this.out = out; var s = this.streams; var L = s.length; for (var i = 0; i < L; i++) { s[i]._add(this); } }; MergeProducer.prototype._stop = function () { var s = this.streams; var L = s.length; for (var i = 0; i < L; i++) { s[i]._remove(this); } this.out = null; this.ac = L; }; MergeProducer.prototype._n = function (t) { var u = this.out; if (!u) return; u._n(t); }; MergeProducer.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; MergeProducer.prototype._c = function () { if (--this.ac === 0) { var u = this.out; if (!u) return; u._c(); } }; return MergeProducer; }()); exports.MergeProducer = MergeProducer; var PeriodicProducer = (function () { function PeriodicProducer(period) { this.period = period; this.type = 'periodic'; this.intervalID = -1; this.i = 0; } PeriodicProducer.prototype._start = function (stream) { var self = this; function intervalHandler() { stream._n(self.i++); } this.intervalID = setInterval(intervalHandler, this.period); }; PeriodicProducer.prototype._stop = function () { if (this.intervalID !== -1) clearInterval(this.intervalID); this.intervalID = -1; this.i = 0; }; return PeriodicProducer; }()); exports.PeriodicProducer = PeriodicProducer; var DebugOperator = (function () { function DebugOperator(spy, ins) { if (spy === void 0) { spy = null; } this.spy = spy; this.ins = ins; this.type = 'debug'; this.out = null; } DebugOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; DebugOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; }; DebugOperator.prototype._n = function (t) { var u = this.out; if (!u) return; var spy = this.spy; if (spy) { try { spy(t); } catch (e) { u._e(e); } } else { console.log(t); } u._n(t); }; DebugOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; DebugOperator.prototype._c = function () { var u = this.out; if (!u) return; u._c(); }; return DebugOperator; }()); exports.DebugOperator = DebugOperator; var DropOperator = (function () { function DropOperator(max, ins) { this.max = max; this.ins = ins; this.type = 'drop'; this.out = null; this.dropped = 0; } DropOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; DropOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; this.dropped = 0; }; DropOperator.prototype._n = function (t) { var u = this.out; if (!u) return; if (this.dropped++ >= this.max) u._n(t); }; DropOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; DropOperator.prototype._c = function () { var u = this.out; if (!u) return; u._c(); }; return DropOperator; }()); exports.DropOperator = DropOperator; var OtherIL = (function () { function OtherIL(out, op) { this.out = out; this.op = op; } OtherIL.prototype._n = function (t) { this.op.end(); }; OtherIL.prototype._e = function (err) { this.out._e(err); }; OtherIL.prototype._c = function () { this.op.end(); }; return OtherIL; }()); var EndWhenOperator = (function () { function EndWhenOperator(o, // o = other ins) { this.o = o; this.ins = ins; this.type = 'endWhen'; this.out = null; this.oil = exports.emptyListener; // oil = other InternalListener } EndWhenOperator.prototype._start = function (out) { this.out = out; this.o._add(this.oil = new OtherIL(out, this)); this.ins._add(this); }; EndWhenOperator.prototype._stop = function () { this.ins._remove(this); this.o._remove(this.oil); this.out = null; this.oil = null; }; EndWhenOperator.prototype.end = function () { var u = this.out; if (!u) return; u._c(); }; EndWhenOperator.prototype._n = function (t) { var u = this.out; if (!u) return; u._n(t); }; EndWhenOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; EndWhenOperator.prototype._c = function () { this.end(); }; return EndWhenOperator; }()); exports.EndWhenOperator = EndWhenOperator; var FilterOperator = (function () { function FilterOperator(passes, ins) { this.passes = passes; this.ins = ins; this.type = 'filter'; this.out = null; } FilterOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; FilterOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; }; FilterOperator.prototype._n = function (t) { var u = this.out; if (!u) return; try { if (this.passes(t)) u._n(t); } catch (e) { u._e(e); } }; FilterOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; FilterOperator.prototype._c = function () { var u = this.out; if (!u) return; u._c(); }; return FilterOperator; }()); exports.FilterOperator = FilterOperator; var FCIL = (function () { function FCIL(out, op) { this.out = out; this.op = op; } FCIL.prototype._n = function (t) { this.out._n(t); }; FCIL.prototype._e = function (err) { this.out._e(err); }; FCIL.prototype._c = function () { this.op.less(); }; return FCIL; }()); var FlattenConcOperator = (function () { function FlattenConcOperator(ins) { this.ins = ins; this.type = 'flattenConcurrently'; this.active = 1; // number of outers and inners that have not yet ended this.out = null; } FlattenConcOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; FlattenConcOperator.prototype._stop = function () { this.ins._remove(this); this.active = 1; this.out = null; }; FlattenConcOperator.prototype.less = function () { if (--this.active === 0) { var u = this.out; if (!u) return; u._c(); } }; FlattenConcOperator.prototype._n = function (s) { var u = this.out; if (!u) return; this.active++; s._add(new FCIL(u, this)); }; FlattenConcOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; FlattenConcOperator.prototype._c = function () { this.less(); }; return FlattenConcOperator; }()); exports.FlattenConcOperator = FlattenConcOperator; var FIL = (function () { function FIL(out, op) { this.out = out; this.op = op; } FIL.prototype._n = function (t) { this.out._n(t); }; FIL.prototype._e = function (err) { this.out._e(err); }; FIL.prototype._c = function () { this.op.inner = null; this.op.less(); }; return FIL; }()); var FlattenOperator = (function () { function FlattenOperator(ins) { this.ins = ins; this.type = 'flatten'; this.inner = null; // Current inner Stream this.il = null; // Current inner InternalListener this.open = true; this.out = null; } FlattenOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; FlattenOperator.prototype._stop = function () { this.ins._remove(this); this.inner = null; this.il = null; this.open = true; this.out = null; }; FlattenOperator.prototype.less = function () { var u = this.out; if (!u) return; if (!this.open && !this.inner) u._c(); }; FlattenOperator.prototype._n = function (s) { var u = this.out; if (!u) return; var _a = this, inner = _a.inner, il = _a.il; if (inner && il) inner._remove(il); (this.inner = s)._add(this.il = new FIL(u, this)); }; FlattenOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; FlattenOperator.prototype._c = function () { this.open = false; this.less(); }; return FlattenOperator; }()); exports.FlattenOperator = FlattenOperator; var FoldOperator = (function () { function FoldOperator(f, seed, ins) { this.f = f; this.seed = seed; this.ins = ins; this.type = 'fold'; this.out = null; this.acc = seed; } FoldOperator.prototype._start = function (out) { this.out = out; out._n(this.acc); this.ins._add(this); }; FoldOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; this.acc = this.seed; }; FoldOperator.prototype._n = function (t) { var u = this.out; if (!u) return; try { u._n(this.acc = this.f(this.acc, t)); } catch (e) { u._e(e); } }; FoldOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; FoldOperator.prototype._c = function () { var u = this.out; if (!u) return; u._c(); }; return FoldOperator; }()); exports.FoldOperator = FoldOperator; var LastOperator = (function () { function LastOperator(ins) { this.ins = ins; this.type = 'last'; this.out = null; this.has = false; this.val = empty; } LastOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; LastOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; this.has = false; this.val = empty; }; LastOperator.prototype._n = function (t) { this.has = true; this.val = t; }; LastOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; LastOperator.prototype._c = function () { var u = this.out; if (!u) return; if (this.has) { u._n(this.val); u._c(); } else { u._e('TODO show proper error'); } }; return LastOperator; }()); exports.LastOperator = LastOperator; var MFCIL = (function () { function MFCIL(out, op) { this.out = out; this.op = op; } MFCIL.prototype._n = function (r) { this.out._n(r); }; MFCIL.prototype._e = function (err) { this.out._e(err); }; MFCIL.prototype._c = function () { this.op.less(); }; return MFCIL; }()); var MapFlattenConcOperator = (function () { function MapFlattenConcOperator(mapOp) { this.mapOp = mapOp; this.active = 1; // number of outers and inners that have not yet ended this.out = null; this.type = mapOp.type + "+flattenConcurrently"; this.ins = mapOp.ins; } MapFlattenConcOperator.prototype._start = function (out) { this.out = out; this.mapOp.ins._add(this); }; MapFlattenConcOperator.prototype._stop = function () { this.mapOp.ins._remove(this); this.active = 1; this.out = null; }; MapFlattenConcOperator.prototype.less = function () { if (--this.active === 0) { var u = this.out; if (!u) return; u._c(); } }; MapFlattenConcOperator.prototype._n = function (v) { var u = this.out; if (!u) return; this.active++; try { this.mapOp.project(v)._add(new MFCIL(u, this)); } catch (e) { u._e(e); } }; MapFlattenConcOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; MapFlattenConcOperator.prototype._c = function () { this.less(); }; return MapFlattenConcOperator; }()); exports.MapFlattenConcOperator = MapFlattenConcOperator; var MFIL = (function () { function MFIL(out, op) { this.out = out; this.op = op; } MFIL.prototype._n = function (r) { this.out._n(r); }; MFIL.prototype._e = function (err) { this.out._e(err); }; MFIL.prototype._c = function () { this.op.inner = null; this.op.less(); }; return MFIL; }()); var MapFlattenOperator = (function () { function MapFlattenOperator(mapOp) { this.mapOp = mapOp; this.inner = null; // Current inner Stream this.il = null; // Current inner InternalListener this.open = true; this.out = null; this.type = mapOp.type + "+flatten"; this.ins = mapOp.ins; } MapFlattenOperator.prototype._start = function (out) { this.out = out; this.mapOp.ins._add(this); }; MapFlattenOperator.prototype._stop = function () { this.mapOp.ins._remove(this); this.inner = null; this.il = null; this.open = true; this.out = null; }; MapFlattenOperator.prototype.less = function () { if (!this.open && !this.inner) { var u = this.out; if (!u) return; u._c(); } }; MapFlattenOperator.prototype._n = function (v) { var u = this.out; if (!u) return; var _a = this, inner = _a.inner, il = _a.il; if (inner && il) inner._remove(il); try { (this.inner = this.mapOp.project(v))._add(this.il = new MFIL(u, this)); } catch (e) { u._e(e); } }; MapFlattenOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; MapFlattenOperator.prototype._c = function () { this.open = false; this.less(); }; return MapFlattenOperator; }()); exports.MapFlattenOperator = MapFlattenOperator; var MapOperator = (function () { function MapOperator(project, ins) { this.project = project; this.ins = ins; this.type = 'map'; this.out = null; } MapOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; MapOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; }; MapOperator.prototype._n = function (t) { var u = this.out; if (!u) return; try { u._n(this.project(t)); } catch (e) { u._e(e); } }; MapOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; MapOperator.prototype._c = function () { var u = this.out; if (!u) return; u._c(); }; return MapOperator; }()); exports.MapOperator = MapOperator; var FilterMapOperator = (function (_super) { __extends(FilterMapOperator, _super); function FilterMapOperator(passes, project, ins) { _super.call(this, project, ins); this.passes = passes; this.type = 'filter+map'; } FilterMapOperator.prototype._n = function (v) { if (this.passes(v)) { _super.prototype._n.call(this, v); } ; }; return FilterMapOperator; }(MapOperator)); exports.FilterMapOperator = FilterMapOperator; var ReplaceErrorOperator = (function () { function ReplaceErrorOperator(fn, ins) { this.fn = fn; this.ins = ins; this.type = 'replaceError'; this.out = empty; } ReplaceErrorOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; ReplaceErrorOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; }; ReplaceErrorOperator.prototype._n = function (t) { var u = this.out; if (!u) return; u._n(t); }; ReplaceErrorOperator.prototype._e = function (err) { var u = this.out; if (!u) return; try { this.ins._remove(this); (this.ins = this.fn(err))._add(this); } catch (e) { u._e(e); } }; ReplaceErrorOperator.prototype._c = function () { var u = this.out; if (!u) return; u._c(); }; return ReplaceErrorOperator; }()); exports.ReplaceErrorOperator = ReplaceErrorOperator; var StartWithOperator = (function () { function StartWithOperator(ins, value) { this.ins = ins; this.value = value; this.type = 'startWith'; this.out = exports.emptyListener; } StartWithOperator.prototype._start = function (out) { this.out = out; this.out._n(this.value); this.ins._add(out); }; StartWithOperator.prototype._stop = function () { this.ins._remove(this.out); this.out = null; }; return StartWithOperator; }()); exports.StartWithOperator = StartWithOperator; var TakeOperator = (function () { function TakeOperator(max, ins) { this.max = max; this.ins = ins; this.type = 'take'; this.out = null; this.taken = 0; } TakeOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; TakeOperator.prototype._stop = function () { this.ins._remove(this); this.out = null; this.taken = 0; }; TakeOperator.prototype._n = function (t) { var u = this.out; if (!u) return; if (this.taken++ < this.max - 1) { u._n(t); } else { u._n(t); u._c(); this._stop(); } }; TakeOperator.prototype._e = function (err) { var u = this.out; if (!u) return; u._e(err); }; TakeOperator.prototype._c = function () { var u = this.out; if (!u) return; u._c(); }; return TakeOperator; }()); exports.TakeOperator = TakeOperator; var Stream = (function () { function Stream(producer) { this._stopID = empty; /** * Combines multiple streams with the input stream to return a stream whose * events are calculated from the latest events of each of its input streams. * * *combine* remembers the most recent event from each of the input streams. * When any of the input streams emits an event, that event together with all * the other saved events are combined in the `project` function which should * return a value. That value will be emitted on the output stream. It's * essentially a way of mixing the events from multiple streams according to a * formula. * * Marble diagram: * * ```text * --1----2-----3--------4--- * ----a-----b-----c--d------ * combine((x,y) => x+y) * ----1a-2a-2b-3b-3c-3d-4d-- * ``` * * @param {Function} project A function of type `(x: T1, y: T2) => R` or * similar that takes the most recent events `x` and `y` from the input * streams and returns a value. The output stream will emit that value. The * number of arguments for this function should match the number of input * streams. * @param {Stream} other Another stream to combine together with the input * stream. There may be more of these arguments. * @return {Stream} */ this.combine = function combine(project) { var streams = []; for (var _i = 1; _i < arguments.length; _i++) { streams[_i - 1] = arguments[_i]; } streams.unshift(this); return Stream.combine.apply(Stream, [project].concat(streams)); }; this._prod = producer; this._ils = []; } Stream.prototype._n = function (t) { var a = this._ils; var L = a.length; if (L == 1) a[0]._n(t); else { var b = copy(a); for (var i = 0; i < L; i++) b[i]._n(t); } }; Stream.prototype._e = function (err) { var a = this._ils; var L = a.length; if (L == 1) a[0]._e(err); else { var b = copy(a); for (var i = 0; i < L; i++) b[i]._e(err); } this._x(); }; Stream.prototype._c = function () { var a = this._ils; var L = a.length; if (L == 1) a[0]._c(); else { var b = copy(a); for (var i = 0; i < L; i++) b[i]._c(); } this._x(); }; Stream.prototype._x = function () { if (this._ils.length === 0) return; if (this._prod) this._prod._stop(); this._ils = []; }; /** * Adds a Listener to the Stream. * * @param {Listener<T>} listener */ Stream.prototype.addListener = function (listener) { if (typeof listener.next !== 'function' || typeof listener.error !== 'function' || typeof listener.complete !== 'function') { throw new Error('stream.addListener() requires all three next, error, ' + 'and complete functions.'); } listener._n = listener.next; listener._e = listener.error; listener._c = listener.complete; this._add(listener); }; /** * Removes a Listener from the Stream, assuming the Listener was added to it. * * @param {Listener<T>} listener */ Stream.prototype.removeListener = function (listener) { this._remove(listener); }; Stream.prototype._add = function (il) { var a = this._ils; a.push(il); if (a.length === 1) { if (this._stopID !== empty) { clearTimeout(this._stopID); this._stopID = empty; } var p = this._prod; if (p) p._start(this); } }; Stream.prototype._remove = function (il) { var a = this._ils; var i = a.indexOf(il); if (i > -1) { a.splice(i, 1); var p_1 = this._prod; if (p_1 && a.length <= 0) { this._stopID = setTimeout(function () { return p_1._stop(); }); } } }; /** * Creates a new Stream given a Producer. * * @factory true * @param {Producer} producer An optional Producer that dictates how to * start, generate events, and stop the Stream. * @return {Stream} */ Stream.create = function (producer) { if (producer) { if (typeof producer.start !== 'function' || typeof producer.stop !== 'function') { throw new Error('producer requires both start and stop functions'); } internalizeProducer(producer); // mutates the input } return new Stream(producer); }; /** * Creates a new MemoryStream given a Producer. * * @factory true * @param {Producer} producer An optional Producer that dictates how to * start, generate events, and stop the Stream. * @return {MemoryStream} */ Stream.createWithMemory = function (producer) { if (producer) { internalizeProducer(producer); // mutates the input } return new MemoryStream(producer); }; /** * Creates a Stream that does nothing when started. It never emits any event. * * Marble diagram: * * ```text * never * ----------------------- * ``` * * @factory true * @return {Stream} */ Stream.never = function () { return new Stream({ _start: noop, _stop: noop }); }; /** * Creates a Stream that immediately emits the "complete" notification when * started, and that's it. * * Marble diagram: * * ```text * empty * -| * ``` * * @factory true * @return {Stream} */ Stream.empty = function () { return new Stream({ _start: function (il) { il._c(); }, _stop: noop, }); }; /** * Creates a Stream that immediately emits an "error" notification with the * value you passed as the `error` argument when the stream starts, and that's * it. * * Marble diagram: * * ```text * throw(X) * -X * ``` * * @factory true * @param error The error event to emit on the created stream. * @return {Stream} */ Stream.throw = function (error) { return new Stream({ _start: function (il) { il._e(error); }, _stop: noop, }); }; /** * Creates a Stream that immediately emits the arguments that you give to * *of*, then completes. * * Marble diagram: * * ```text * of(1,2,3) * 123| * ``` * * @factory true * @param a The first value you want to emit as an event on the stream. * @param b The second value you want to emit as an event on the stream. One * or more of these values may be given as arguments. * @return {Stream} */ Stream.of = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i - 0] = arguments[_i]; } return Stream.fromArray(items); }; /** * Converts an array to a stream. The returned stream will emit synchronously * all the items in the array, and then complete. * * Marble diagram: * * ```text * fromArray([1,2,3]) * 123| * ``` * * @factory true * @param {Array} array The array to be converted as a stream. * @return {Stream} */ Stream.fromArray = function (array) { return new Stream(new FromArrayProducer(array)); }; /** * Converts a promise to a stream. The returned stream will emit the resolved * value of the promise, and then complete. However, if the promise is * rejected, the stream will emit the corresponding error. * * Marble diagram: * * ```text * fromPromise( ----42 ) * -----------------42| * ``` * * @factory true * @param {Promise} promise The promise to be converted as a stream. * @return {Stream} */ Stream.fromPromise = function (promise) { return new Stream(new FromPromiseProducer(promise)); }; /** * Creates a stream that periodically emits incremental numbers, every * `period` milliseconds. * * Marble diagram: * * ```text * periodic(1000) * ---0---1---2---3---4---... * ``` * * @factory true * @param {number} period The interval in milliseconds to use as a rate of * emission. * @return {Stream} */ Stream.periodic = function (period) { return new Stream(new PeriodicProducer(period)); }; /** * Blends multiple streams together, emitting events from all of them * concurrently. * * *merge* takes multiple streams as arguments, and creates a stream that * imitates each of the argument streams, in parallel. * * Marble diagram: * * ```text * --1----2-----3--------4--- * ----a-----b----c---d------ * merge * --1-a--2--b--3-c---d--4--- * ``` * * @factory true * @param {Stream} stream1 A stream to merge together with other streams. * @param {Stream} stream2 A stream to merge together with other streams. Two * or more streams may be given as arguments. * @return {Stream} */ Stream.merge = function () { var streams = []; for (var _i = 0; _i < arguments.length; _i++) { streams[_i - 0] = arguments[_i]; } return new Stream(new MergeProducer(streams)); }; /** * Transforms each event from the input Stream through a `project` function, * to get a Stream that emits those transformed events. * * Marble diagram: * * ```text * --1---3--5-----7------ * map(i => i * 10) * --10--30-50----70----- * ``` * * @param {Function} project A function of type `(t: T) => U` that takes event * `t` of type `T` from the input Stream and produces an event of type `U`, to * be emitted on the output Stream. * @return {Stream} */ Stream.prototype.map = function (project) { var p = this._prod; if (p instanceof FilterOperator) { return new Stream(new FilterMapOperator(p.passes, project, p.ins)); } if (p instanceof FilterMapOperator) { return new Stream(new FilterMapOperator(p.passes, compose2(project, p.project), p.ins)); } if (p instanceof MapOperator) { return new Stream(new MapOperator(compose2(project, p.project), p.ins)); } return new Stream(new MapOperator(project, this)); }; /** * It's like `map`, but transforms each input event to always the same * constant value on the output Stream. * * Marble diagram: * * ```text * --1---3--5-----7----- * mapTo(10) * --10--10-10----10---- * ``` * * @param projectedValue A value to emit on the output Stream whenever the * input Stream emits any value. * @return {Stream} */ Stream.prototype.mapTo = function (projectedValue) { var s = this.map(function () { return projectedValue; }); var op = s._prod; op.type = op.type.replace('map', 'mapTo'); return s; }; /** * Only allows events that pass the test given by the `passes` argument. * * Each event from the input stream is given to the `passes` function. If the * function returns `true`, the event is forwarded to the output stream, * otherwise it is ignored and not forwarded. * * Marble diagram: * * ```text * --1---2--3-----4-----5---6--7-8-- * filter(i => i % 2 === 0) * ------2--------4---------6----8-- * ``` * * @param {Function} passes A function of type `(t: T) +> boolean` that takes * an event from the input stream and checks if it passes, by returning a * boolean. * @return {Stream} */ Stream.prototype.filter = function (passes) { var p = this._prod; if (p instanceof FilterOperator) { return new Stream(new FilterOperator(and(passes, p.passes), p.ins)); } return new Stream(new FilterOperator(passes, this)); }; /** * Lets the first `amount` many events from the input stream pass to the * output stream, then makes the output stream complete. * * Marble diagram: * * ```text * --a---b--c----d---e-- * take(3) * --a---b--c| * ``` * * @param {number} amount How many events to allow from the input stream * before completing the output stream. * @return {Stream} */ Stream.prototype.take = function (amount) { return new Stream(new TakeOperator(amount, this)); }; /** * Ignores the first `amount` many events from the input stream, and then * after that starts forwarding events from the input stream to the output * stream. * * Marble diagram: * * ```text * --a---b--c----d---e-- * drop(3) * --------------d---e-- * ``` * * @param {number} amount How many events to ignore from the input stream * before forwarding all events from the input stream to the output stream. * @return {Stream} */ Stream.prototype.drop = function (amount) { return new Stream(new DropOperator(amount, this)); }; /** * When the input stream completes, the output stream will emit the last event * emitted by the input stream, and then will also complete. * * Marble diagram: * * ```text * --a---b--c--d----| * last() * -----------------d| * ``` * * @return {Stream} */ Stream.prototype.last = function () { return new Stream(new LastOperator(this)); }; /** * Prepends the given `initial` value to the sequence of events emitted by the * input stream. * * Marble diagram: * * ```text * ---1---2-----3--- * startWith(0) * 0--1---2-----3--- * ``` * * @param initial The value or event to prepend. * @return {Stream} */ Stream.prototype.startWith = function (initial) { return new Stream(new StartWithOperator(this, initial)); }; /** * Uses another stream to determine when to complete the current stream. * * When the given `other` stream emits an event or completes, the output * stream will complete. Before that happens, the output stream will imitate * whatever happens on the input stream. * * Marble diagram: * * ```text * ---1---2-----3--4----5----6--- * endWhen( --------a--b--| ) * ---1---2-----3--4--| * ``` * * @param other Some other stream that is used to know when should the output * stream of this operator complete. * @return {Stream} */ Stream.prototype.endWhen = function (other) { return new Stream(new EndWhenOperator(other, this)); }; /** * "Folds" the stream onto itself. * * Combines events from the past throughout * the entire execution of the input stream, allowing you to accumulate them * together. It's essentially like `Array.prototype.reduce`. * * The output stream starts by emitting the `seed` which you give as argument. * Then, when an event happens on the input stream, it is combined with that * seed value through the `accumulate` function, and the output value is * emitted on the output stream. `fold` remembers that output value as `acc` * ("accumulator"), and then when a new input event `t` happens, `acc` will be * combined with that to produce the new `acc` and so forth. * * Marble diagram: * * ```text * ------1-----1--2----1----1------ * fold((acc, x) => acc + x, 3) * 3-----4-----5--7----8----9------ * ``` * * @param {Function} accumulate A function of type `(acc: R, t: T) => R` that * takes the previous accumulated value `acc` and the incoming event from the * input stream and produces the new accumulated value. * @param seed The initial accumulated value, of type `R`. * @return {Stream} */ Stream.prototype.fold = function (accumulate, seed) { return new Stream(new FoldOperator(accumulate, seed, this)); }; /** * Replaces an error with another stream. * * When (and if) an error happens on the input stream, instead of forwarding * that error to the output stream, *replaceError* will call the `replace` * function which returns the stream that the output stream will imitate. And, * in case that new stream also emits an error, `replace` will be called again * to get another stream to start imitating. * * Marble diagram: * * ```text * --1---2-----3--4-----X * replaceError( () => --10--| ) * --1---2-----3--4--------10--| * ``` * * @param {Function} replace A function of type `(err) => Stream` that takes * the error that occurred on the input stream or on the previous replacement * stream and returns a new stream. The output stream will imitate the stream * that this function returns. * @return {Stream} */ Stream.prototype.replaceError = function (replace) { return new Stream(new ReplaceErrorOperator(replace, this)); }; /** * Flattens a "stream of streams", handling only one nested stream at a time * (no concurrency). * * If the input stream is a stream that emits streams, then this operator will * return an output stream which is a flat stream: emits regular events. The * flattening happens without concurrency. It works like this: when the input * stream emits a nested stream, *flatten* will start imitating that nested * one. However, as soon as the next nested stream is emitted on the input * stream, *flatten* will forget the previous nested one it was imitating, and * will start imitating the new nested one. * * Marble diagram: * * ```text * --+--------+--------------- * \ \ * \ ----1----2---3-- * --a--b----c----d-------- * flatten * -----a--b------1----2---3-- * ``` * * @return {Stream} */ Stream.prototype.flatten = function () { var p = this._prod; return new Stream(p instanceof MapOperator && !(p instanceof FilterMapOperator) ? new MapFlattenOperator(p) : new FlattenOperator(this)); }; /** * Flattens a "stream of streams", handling multiple concurrent nested streams * simultaneously. * * If the input stream is a stream that emits streams, then this operator will * return an output stream which is a flat stream: emits regular events. The * flattening happens concurrently. It works like this: when the input stream * emits a nested stream, *flattenConcurrently* will start imitating that * nested one. When the next nested stream is emitted on the input stream, * *flattenConcurrently* will also imitate that new one, but will continue to * imitate the previous nested streams as well. * * Marble diagram: * * ```text * --+--------+--------------- * \ \ * \ ----1----2---3-- * --a--b----c----d-------- * flattenConcurrently * -----a--b----c-1--d-2---3-- * ``` * * @return {Stream} */ Stream.prototype.flattenConcurrently = function () { var p = this._prod; return new Stream(p instanceof MapOperator && !(p instanceof FilterMapOperator) ? new MapFlattenConcOperator(p) : new FlattenConcOperator(this)); }; /** * Blends two streams together, emitting events from both. * * *merge* takes an `other` stream and returns an output stream that imitates * both the input stream and the `other` stream. * * Marble diagram: * * ```text * --1----2-----3--------4--- * ----a-----b----c---d------ * merge * --1-a--2--b--3-c---d--4--- * ``` * * @param {Stream} other Another stream to merge together with the input * stream. * @return {Stream} */ Stream.prototype.merge = function (other) { return Stream.merge(this, other); }; /** * Passes the input stream to a custom operator, to produce an output stream. * * *compose* is a handy way of using an existing function in a chained style. * Instead of writing `outStream = f(inStream)` you can write * `outStream = inStream.compose(f)`. * * @param {function} operator A function that takes a stream as input and * returns a stream as well. * @return {Stream} */ Stream.prototype.compose = function (operator) { return operator(this); }; /** * Returns an output stream that imitates the input stream, but also remembers * the most recent event that happens on the input stream, so that a newly * added listener will immediately receive that memorised event. * * @return {MemoryStream} */ Stream.prototype.remember = function () { var _this = this; return new MemoryStream({ _start: function (il) { _this._prod._start(il); }, _stop: function () { _this._prod._stop(); }, }); }; /** * Changes this current stream to imitate the `other` given stream. * * The *imitate* method returns nothing. Instead, it changes the behavior of * the current stream, making it re-emit whatever events are emitted by the * given `other` stream. * @param {Stream} other The stream to imitate on the current one. */ Stream.prototype.imitate = function (other) { other._add(this); }; /** * Returns an output stream that identically imitates the input stream, but * also runs a `spy` function fo each event, to help you debug your app. * * *debug* takes a `spy` function as argument, and runs that for each event * happening on the input stream. If you don't provide the `spy` argument, * then *debug* will just `console.log` each event. This helps you to * understand the flow of events through some operator chain. * * Please note that if the output stream has no listeners, then it will not * start, which means `spy` will never run because no actual event happens in * that case. * * Marble diagram: * * ```text * --1----2-----3-----4-- * debug * --1----2-----3-----4-- * ``` * * @param {function} spy A function that takes an event as argument, and * returns nothing. * @return {Stream} */ Stream.prototype.debug = function (spy) { if (spy === void 0) { spy = null; } return new Stream(new DebugOperator(spy, this)); }; /** * Forces the Stream to emit the given value to its listeners. * * As the name indicates, if you use this, you are most likely doing something * The Wrong Way. Please try to understand the reactive way before using this * method. Use it only when you know what you are doing. * * @param value The "next" value you want to broadcast to all listeners of * this Stream. */ Stream.prototype.shamefullySendNext = function (value) { this._n(value); }; /** * Forces the Stream to emit the given error to its listeners. * * As the name indicates, if you use this, you are most likely doing something * The Wrong Way. Please try to understand the reactive way before using this * method. Use it only when you know what you are doing. * * @param {any} error The error you want to broadcast to all the listeners of * this Stream. */ Stream.prototype.shamefullySendError = function (error) { this._e(error); }; /** * Forces the Stream to emit the "completed" event to its listeners. * * As the name indicates, if you use this, you are most likely doing something * The Wrong Way. Please try to understand the reactive way before using this * method. Use it only when you know what you are doing. */ Stream.prototype.shamefullySendComplete = function () { this._c(); }; /** * Combines multiple streams together to return a stream whose events are * calculated from the latest events of each of the input streams. * * *combine* remembers the most recent event from each of the input streams. * When any of the input streams emits an event, that event together with all * the other saved events are combined in the `project` function which should * return a value. That value will be emitted on the output stream. It's * essentially a way of mixing the events from multiple streams according to a * formula. * * Marble diagram: * * ```text * --1----2-----3--------4--- * ----a-----b-----c--d------ * combine((x,y) => x+y) * ----1a-2a-2b-3b-3c-3d-4d-- * ``` * * @factory true * @param {Function} project A function of type `(x: T1, y: T2) => R` or * similar that takes the most recent events `x` and `y` from the input * streams and returns a value. The output stream will emit that value. The * number of arguments for this function should match the number of input * streams. * @param {Stream} stream1 A stream to combine together with other streams. * @param {Stream} stream2 A stream to combine together with other streams. * Two or more streams may be given as arguments. * @return {Stream} */ Stream.combine = function combine(project) { var streams = []; for (var _i = 1; _i < arguments.length; _i++) { streams[_i - 1] = arguments[_i]; } return new Stream(new CombineProducer(project, streams)); }; return Stream; }()); exports.Stream = Stream; var MemoryStream = (function (_super) { __extends(MemoryStream, _super); function MemoryStream(producer) { _super.call(this, producer); this._has = false; } MemoryStream.prototype._n = function (x) { this._v = x; this._has = true; _super.prototype._n.call(this, x); }; MemoryStream.prototype._add = function (il) { if (this._has) { il._n(this._v); } _super.prototype._add.call(this, il); }; return MemoryStream; }(Stream)); exports.MemoryStream = MemoryStream; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Stream; },{}],62:[function(require,module,exports){ "use strict"; var core_1 = require('../core'); var ConcatProducer = (function () { function ConcatProducer(streams) { this.streams = streams; this.type = 'concat'; this.out = null; this.i = 0; } ConcatProducer.prototype._start = function (out) { this.out = out; this.streams[this.i]._add(this); }; ConcatProducer.prototype._stop = function () { var streams = this.streams; if (this.i < streams.length) { streams[this.i]._remove(this); } this.i = 0; this.out = null; }; ConcatProducer.prototype._n = function (t) { this.out._n(t); }; ConcatProducer.prototype._e = function (err) { this.out._e(err); }; ConcatProducer.prototype._c = function () { var streams = this.streams; streams[this.i]._remove(this); if (++this.i < streams.length) { streams[this.i]._add(this); } else { this.out._c(); } }; return ConcatProducer; }()); function concat() { var streams = []; for (var _i = 0; _i < arguments.length; _i++) { streams[_i - 0] = arguments[_i]; } return new core_1.Stream(new ConcatProducer(streams)); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = concat; },{"../core":61}]},{},[9])(9) });
components/ViroParticleEmitter.js
viromedia/viro
/** * Copyright (c) 2017-present, Viro Media, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViroParticleEmitter * @flow */ 'use strict'; import { requireNativeComponent, View, findNodeHandle } from 'react-native'; import React from 'react'; import resolveAssetSource from "react-native/Libraries/Image/resolveAssetSource"; import { checkMisnamedProps } from './Utilities/ViroProps'; var NativeModules = require('react-native').NativeModules; var createReactClass = require('create-react-class'); import PropTypes from 'prop-types'; var StyleSheet = require('react-native/Libraries/StyleSheet/StyleSheet'); var ViroPropTypes = require('./Styles/ViroPropTypes'); var StyleSheetPropType = require('react-native/Libraries/DeprecatedPropTypes/DeprecatedStyleSheetPropType'); var stylePropType = StyleSheetPropType(ViroPropTypes); var ColorPropType = require('react-native').ColorPropType; var processColor = require('react-native').processColor; var ViroParticleEmitter = createReactClass({ propTypes: { ...View.propTypes, position: PropTypes.arrayOf(PropTypes.number), rotation: PropTypes.arrayOf(PropTypes.number), scale: PropTypes.arrayOf(PropTypes.number), scalePivot: PropTypes.arrayOf(PropTypes.number), rotationPivot: PropTypes.arrayOf(PropTypes.number), onTransformUpdate: PropTypes.func, renderingOrder: PropTypes.number, visible: PropTypes.bool, viroTag: PropTypes.string, transformBehaviors: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.string ]), highAccuracyEvents:PropTypes.bool, duration: PropTypes.number, delay: PropTypes.number, loop: PropTypes.bool, run: PropTypes.bool, fixedToEmitter : PropTypes.bool, image: PropTypes.shape({ source : PropTypes.oneOfType([ PropTypes.shape({ uri: PropTypes.string, }), PropTypes.number ]).isRequired, height: PropTypes.number, width: PropTypes.number, bloomThreshold: PropTypes.number, blendMode: PropTypes.string, }).isRequired, spawnBehavior: PropTypes.shape({ emissionRatePerSecond: PropTypes.arrayOf(PropTypes.number), emissionRatePerMeter: PropTypes.arrayOf(PropTypes.number), particleLifetime: PropTypes.arrayOf(PropTypes.number), maxParticles: PropTypes.number, emissionBurst: PropTypes.arrayOf(PropTypes.oneOfType([ PropTypes.shape({ time: PropTypes.number, min: PropTypes.number, max: PropTypes.number, cycles: PropTypes.number, cooldownPeriod: PropTypes.number, }), PropTypes.shape({ distance: PropTypes.number, min: PropTypes.number, max: PropTypes.number, cycles: PropTypes.number, cooldownDistance: PropTypes.number, }), ])), spawnVolume: PropTypes.shape({ shape: PropTypes.string, params: PropTypes.arrayOf(PropTypes.number), spawnOnSurface:PropTypes.bool }), }), particleAppearance: PropTypes.shape({ opacity: PropTypes.shape({ initialRange: PropTypes.arrayOf(PropTypes.number), factor: PropTypes.oneOf(["Time", "Distance"]), interpolation: PropTypes.arrayOf(PropTypes.shape({ interval: PropTypes.arrayOf(PropTypes.number), endValue: PropTypes.number, })), }), scale: PropTypes.shape({ initialRange: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.number)), factor: PropTypes.oneOf(["Time", "Distance"]), interpolation: PropTypes.arrayOf(PropTypes.shape({ interval: PropTypes.arrayOf(PropTypes.number), endValue: PropTypes.arrayOf(PropTypes.number), })), }), // rotation is only about the Z axis rotation: PropTypes.shape({ initialRange: PropTypes.arrayOf(PropTypes.number), factor: PropTypes.oneOf(["Time", "Distance"]), interpolation: PropTypes.arrayOf(PropTypes.shape({ interval: PropTypes.arrayOf(PropTypes.number), endValue: PropTypes.number, })), }), color: PropTypes.shape({ initialRange: PropTypes.arrayOf(ColorPropType), factor: PropTypes.oneOf(["Time", "Distance"]), interpolation: PropTypes.arrayOf(PropTypes.shape({ interval: PropTypes.arrayOf(PropTypes.number), endValue: ColorPropType, })), }), }), particlePhysics: PropTypes.shape({ velocity: PropTypes.shape({ initialRange: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.number)), }), acceleration: PropTypes.shape({ initialRange: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.number)), }), explosiveImpulse:PropTypes.shape({ impulse: PropTypes.number, position: PropTypes.arrayOf(PropTypes.number), decelerationPeriod: PropTypes.number, }), }), }, getInitialState: function() { return { propsPositionState:this.props.position, nativePositionState:undefined } }, async getTransformAsync() { return await NativeModules.VRTNodeModule.getNodeTransform(findNodeHandle(this)); }, async getBoundingBoxAsync() { return await NativeModules.VRTNodeModule.getBoundingBox(findNodeHandle(this)); }, // Called from native on the event a positional change has occured // for the underlying control within the renderer. _onNativeTransformUpdate: function(event: Event){ var position = event.nativeEvent.position; this.setState({ nativePositionState:position }, () => { if (this.props.onTransformUpdate){ this.props.onTransformUpdate(position); } }); }, // Ignore all changes in native position state as it is only required to // keep track of the latest position prop set on this control. shouldComponentUpdate: function(nextProps, nextState) { if (nextState.nativePositionState != this.state.nativePositionState){ return false; } return true; }, setNativeProps: function(nativeProps) { this._component.setNativeProps(nativeProps); }, render: function() { checkMisnamedProps("ViroParticleEmitter", this.props); let image = {...this.props.image} if (image.source != undefined) { image.source = resolveAssetSource(image.source); } let transformBehaviors = typeof this.props.transformBehaviors === 'string' ? new Array(this.props.transformBehaviors) : this.props.transformBehaviors; let transformDelegate = this.props.onTransformUpdate != undefined ? this._onNativeTransformUpdate : undefined; // Create native props object. let nativeProps = Object.assign({}, this.props); nativeProps.position = this.state.propsPositionState; nativeProps.onNativeTransformDelegateViro = transformDelegate; nativeProps.hasTransformDelegate = this.props.onTransformUpdate != undefined; nativeProps.image = image; nativeProps.transformBehaviors = transformBehaviors; // For color modifiers, we'll need to processColor for each color value. if (this.props.particleAppearance && this.props.particleAppearance.color){ let colorModifier = this.props.particleAppearance.color; if (colorModifier.initialRange.length != 2){ console.error('The <ViroParticleEmitter> component requires initial value of [min, max] when defining inital rotation property!'); return; } let minColorFinal = processColor(colorModifier.initialRange[0]); let maxColorFinal = processColor(colorModifier.initialRange[1]); let modifierFinal = []; let interpolationLength = colorModifier.interpolation != undefined ? colorModifier.interpolation.length : 0; for (let i = 0; i < interpolationLength; i ++){ let processedColor = processColor(colorModifier.interpolation[i].endValue); let mod = { interval: colorModifier.interpolation[i].interval, endValue: processedColor }; modifierFinal.push(mod); } let newAppearanceColorMod = { initialRange: [minColorFinal, maxColorFinal], factor:colorModifier.factor, interpolation:modifierFinal } nativeProps.particleAppearance.color = newAppearanceColorMod; } // For rotation modifiers, convert degrees to radians, then apply the // Z rotation (due to billboarding for quad particles) if (this.props.particleAppearance && this.props.particleAppearance.rotation){ let rotMod = this.props.particleAppearance.rotation; if (rotMod.initialRange.length != 2){ console.error('The <ViroParticleEmitter> component requires initial value of [min, max] when defining inital rotation property!'); } let minRotFinal = [0,0,rotMod.initialRange[0] * Math.PI / 180]; let maxRotFinal = [0,0,rotMod.initialRange[1] * Math.PI / 180]; let modifierFinal = []; let interpolationLength = rotMod.interpolation != undefined ? rotMod.interpolation.length : 0; for (var i = 0; i < interpolationLength; i ++){ let processedRot = [0,0, rotMod.interpolation[i].endValue * Math.PI / 180]; let mod = { interval: rotMod.interpolation[i].interval, endValue: processedRot }; modifierFinal.push(mod); } let newAppearanceRotMod = { initialRange: [minRotFinal, maxRotFinal], factor:rotMod.factor, interpolation:modifierFinal } nativeProps.particleAppearance.rotation = newAppearanceRotMod; } nativeProps.ref = component => {this._component = component; }; return ( <VRTParticleEmitter {...nativeProps} /> ); }, // Set the propsPositionState on the native control if the // nextProps.position state differs from the nativePositionState that // reflects this control's current vroNode position. statics: { getDerivedStateFromProps(nextProps, prevState) { if (nextProps.position != prevState.nativePositionState) { var newPosition = [nextProps.position[0], nextProps.position[1], nextProps.position[2], Math.random()]; return { propsPositionState:newPosition }; } return {}; } }, }); var VRTParticleEmitter = requireNativeComponent( 'VRTParticleEmitter', ViroParticleEmitter, { nativeOnly: { onNativeTransformDelegateViro:true, hasTransformDelegate:true, canHover: true, canClick: true, canTouch: true, canScroll: true, canSwipe: true, canDrag: true, canPinch: true, canRotate: true, canFuse: true, canCollide: true, onHoverViro: true, onClickViro: true, onTouchViro: true, onScrollViro: true, onSwipeViro: true, onDragViro:true, onPinchViro:true, onRotateViro:true, onPlatformUpdateViro: true, onFuseViro:true, timeToFuse:true, physicsBody:true, onCollisionViro:true, animation:true, materials:true, dragType:true, dragPlane: true, ignoreEventHandling: true, } } ); module.exports = ViroParticleEmitter;
docs/src/sections/ListGroupSection.js
Sipree/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ListGroupSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="listgroup">List group</Anchor> <small>ListGroup, ListGroupItem</small> </h2> <p>List groups are a flexible and powerful component for displaying not only simple lists of elements, but complex ones with custom content.</p> <h3><Anchor id="listgroup-default">Centers by default</Anchor></h3> <ReactPlayground codeText={Samples.ListGroupDefault} /> <h3><Anchor id="listgroup-linked">Linked</Anchor></h3> <p>Set the <code>href</code> or <code>onClick</code> prop on <code>ListGroupItem</code>, to create a linked or clickable element.</p> <ReactPlayground codeText={Samples.ListGroupLinked} /> <h3><Anchor id="listgroup-styling-state">Styling by state</Anchor></h3> <p>Set the <code>active</code> or <code>disabled</code> prop to <code>true</code> to mark or disable the item.</p> <ReactPlayground codeText={Samples.ListGroupActive} /> <h3><Anchor id="listgroup-styling-color">Styling by color</Anchor></h3> <p>Set the <code>bsStyle</code> prop to style the item</p> <ReactPlayground codeText={Samples.ListGroupStyle} /> <h3><Anchor id="listgroup-with-header">With header</Anchor></h3> <p>Set the <code>header</code> prop to create a structured item, with a heading and a body area.</p> <ReactPlayground codeText={Samples.ListGroupHeader} /> <h3><Anchor id="listgroup-with-custom-children">With custom component children</Anchor></h3> <p> When using ListGroupItems directly, ListGroup looks at whether the items have href or onClick props to determine which DOM elements to emit. However, with custom item components as children to <code>ListGroup</code>, set the <code>componentClass</code> prop to specify which element <code>ListGroup</code> should output. </p> <ReactPlayground codeText={Samples.ListGroupCustom} /> <h3><Anchor id="listgroup-props">Props</Anchor></h3> <h4><Anchor id="listgroup-props-group">ListGroup</Anchor></h4> <PropTable component="ListGroup"/> <h4><Anchor id="listgroup-props-item">ListGroupItem</Anchor></h4> <PropTable component="ListGroupItem"/> </div> ); }
src/components/conversations-tutorial-card.js
pol-is/polisClientAdmin
/* * Copyright 2012-present, Polis Technology 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 for non-commercial use can be found in the PATENTS file * in the same directory. */ import React from 'react'; import Radium from 'radium'; import Awesome from "react-fontawesome"; // import _ from 'lodash'; // import Flex from './framework/flex'; // import { connect } from 'react-redux'; // import { FOO } from '../actions'; // const style = { // }; // @connect(state => { // return state.FOO; // }) @Radium class ConversationTutorialCard extends React.Component { constructor(props) { super(props); this.state = { }; } static propTypes = { /* react */ // dispatch: React.PropTypes.func, params: React.PropTypes.object, routes: React.PropTypes.array, /* component api */ style: React.PropTypes.object, title: React.PropTypes.string, awesome: React.PropTypes.string, docs: React.PropTypes.bool, clickHandler: React.PropTypes.func, // foo: React.PropTypes.string } static defaultProps = { title: "Default Tutorial Title", awesome: "plus", docs: false, } getStyles() { return { container: { maxWidth: 300, padding: 20, cursor: "pointer", margin: 20, color: "rgb(100,100,100)", backgroundColor: "rgb(253,253,253)", borderRadius: 3, WebkitBoxShadow: "3px 3px 6px -1px rgba(220,220,220,1)", BoxShadow: "3px 3px 6px -1px rgba(220,220,220,1)" }, awesome: { marginRight: 10 }, heading: { fontWeight: 700 }, body: { fontWeight: 300, lineHeight: 1.7 } }; } render() { const styles = this.getStyles(); return ( <div onClick={this.props.clickHandler} style={[ styles.container, this.props.style ]}> <p style={styles.heading}> <Awesome name={this.props.awesome} style={styles.awesome}/> {this.props.title} </p> <p style={styles.body}> {this.props.body} </p> </div> ); } } export default ConversationTutorialCard; /* propTypes: { // You can declare that a prop is a specific JS primitive. By default, these // are all optional. optionalArray: React.PropTypes.array, optionalBool: React.PropTypes.bool, optionalFunc: React.PropTypes.func, optionalNumber: React.PropTypes.number, optionalObject: React.PropTypes.object, optionalString: React.PropTypes.string, // Anything that can be rendered: numbers, strings, elements or an array // (or fragment) containing these types. optionalNode: React.PropTypes.node, // A React element. optionalElement: React.PropTypes.element, // You can also declare that a prop is an instance of a class. This uses // JS's instanceof operator. optionalMessage: React.PropTypes.instanceOf(Message), // You can ensure that your prop is limited to specific values by treating // it as an enum. optionalEnum: React.PropTypes.oneOf(['News', 'Photos']), // An object that could be one of many types optionalUnion: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.instanceOf(Message) ]), // An array of a certain type optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), // An object with property values of a certain type optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), // An object taking on a particular shape optionalObjectWithShape: React.PropTypes.shape({ color: React.PropTypes.string, fontSize: React.PropTypes.number }), // You can chain any of the above with `isRequired` to make sure a warning // is shown if the prop isn't provided. requiredFunc: React.PropTypes.func.isRequired, // A value of any data type requiredAny: React.PropTypes.any.isRequired, */
docs/src/pages/customization/breakpoints/WithWidth.js
kybarg/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import withWidth from '@material-ui/core/withWidth'; import Typography from '@material-ui/core/Typography'; const components = { sm: 'em', md: 'u', lg: 'del', }; function WithWidth(props) { const { width } = props; const Component = components[width] || 'span'; return ( <Typography variant="subtitle1"> <Component>{`Current width: ${width}`}</Component> </Typography> ); } WithWidth.propTypes = { width: PropTypes.string.isRequired, }; export default withWidth()(WithWidth);
catalog/app/components/Working/index.js
quiltdata/quilt-compiler
/* Authentication progress */ import PropTypes from 'prop-types' import React from 'react' import { styled } from '@material-ui/styles' import Spinner from 'components/Spinner' const Faint = styled('h1')({ fontWeight: 'lighter', opacity: 0.6, }) const Working = ({ children, ...props }) => ( <Faint {...props}> <Spinner /> {children} </Faint> ) Working.propTypes = { children: PropTypes.node, } Working.defaultProps = { children: ' ', } export default Working
ajax/libs/phaser/2.1.3/custom/p2.js
zimbatm/cdnjs
/** * The MIT License (MIT) * * Copyright (c) 2013 p2.js authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ !function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define('p2', (function() { return this.p2 = e(); })()):"undefined"!=typeof window?window.p2=e():"undefined"!=typeof global?self.p2=e():"undefined"!=typeof self&&(self.p2=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ require=(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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})({"PcZj9L":[function(require,module,exports){ var TA = require('typedarray') var xDataView = typeof DataView === 'undefined' ? TA.DataView : DataView var xArrayBuffer = typeof ArrayBuffer === 'undefined' ? TA.ArrayBuffer : ArrayBuffer var xUint8Array = typeof Uint8Array === 'undefined' ? TA.Uint8Array : Uint8Array exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 var browserSupport /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. * * Firefox is a special case because it doesn't allow augmenting "native" object * instances. See `ProxyBuffer` below for more details. */ function Buffer (subject, encoding) { var type = typeof subject // Work-around: node's base64 implementation // allows for non-padded strings while base64-js // does not.. if (encoding === 'base64' && type === 'string') { subject = stringtrim(subject) while (subject.length % 4 !== 0) { subject = subject + '=' } } // Find the length var length if (type === 'number') length = coerce(subject) else if (type === 'string') length = Buffer.byteLength(subject, encoding) else if (type === 'object') length = coerce(subject.length) // Assume object is an array else throw new Error('First argument needs to be a number, array or string.') var buf = augment(new xUint8Array(length)) if (Buffer.isBuffer(subject)) { // Speed optimization -- use set if we're copying from a Uint8Array buf.set(subject) } else if (isArrayIsh(subject)) { // Treat array-ish objects as a byte array. for (var i = 0; i < length; i++) { if (Buffer.isBuffer(subject)) buf[i] = subject.readUInt8(i) else buf[i] = subject[i] } } else if (type === 'string') { buf.write(subject, 0, encoding) } return buf } // STATIC METHODS // ============== Buffer.isEncoding = function(encoding) { switch ((encoding + '').toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true default: return false } } Buffer.isBuffer = function isBuffer (b) { return b && b._isBuffer } Buffer.byteLength = function (str, encoding) { switch (encoding || 'utf8') { case 'hex': return str.length / 2 case 'utf8': case 'utf-8': return utf8ToBytes(str).length case 'ascii': case 'binary': return str.length case 'base64': return base64ToBytes(str).length default: throw new Error('Unknown encoding') } } Buffer.concat = function (list, totalLength) { if (!Array.isArray(list)) { throw new Error('Usage: Buffer.concat(list, [totalLength])\n' + 'list should be an Array.') } var i var buf if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } if (typeof totalLength !== 'number') { totalLength = 0 for (i = 0; i < list.length; i++) { buf = list[i] totalLength += buf.length } } var buffer = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { buf = list[i] buf.copy(buffer, pos) pos += buf.length } return buffer } // INSTANCE METHODS // ================ function _hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) { throw new Error('Invalid hex string') } if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) if (isNaN(byte)) throw new Error('Invalid hex string') buf[offset + i] = byte } Buffer._charsWritten = i * 2 return i } function _utf8Write (buf, string, offset, length) { var bytes, pos return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) } function _asciiWrite (buf, string, offset, length) { var bytes, pos return Buffer._charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) } function _binaryWrite (buf, string, offset, length) { return _asciiWrite(buf, string, offset, length) } function _base64Write (buf, string, offset, length) { var bytes, pos return Buffer._charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) } function BufferWrite (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() switch (encoding) { case 'hex': return _hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return _utf8Write(this, string, offset, length) case 'ascii': return _asciiWrite(this, string, offset, length) case 'binary': return _binaryWrite(this, string, offset, length) case 'base64': return _base64Write(this, string, offset, length) default: throw new Error('Unknown encoding') } } function BufferToString (encoding, start, end) { var self = (this instanceof ProxyBuffer) ? this._proxy : this encoding = String(encoding || 'utf8').toLowerCase() start = Number(start) || 0 end = (end !== undefined) ? Number(end) : end = self.length // Fastpath empty strings if (end === start) return '' switch (encoding) { case 'hex': return _hexSlice(self, start, end) case 'utf8': case 'utf-8': return _utf8Slice(self, start, end) case 'ascii': return _asciiSlice(self, start, end) case 'binary': return _binarySlice(self, start, end) case 'base64': return _base64Slice(self, start, end) default: throw new Error('Unknown encoding') } } function BufferToJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this, 0) } } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) function BufferCopy (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 // Copy 0 bytes; we're done if (end === start) return if (target.length === 0 || source.length === 0) return // Fatal error conditions if (end < start) throw new Error('sourceEnd < sourceStart') if (target_start < 0 || target_start >= target.length) throw new Error('targetStart out of bounds') if (start < 0 || start >= source.length) throw new Error('sourceStart out of bounds') if (end < 0 || end > source.length) throw new Error('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start // copy! for (var i = 0; i < end - start; i++) target[i + target_start] = this[i + start] } function _base64Slice (buf, start, end) { var bytes = buf.slice(start, end) return require('base64-js').fromByteArray(bytes) } function _utf8Slice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' var tmp = '' var i = 0 while (i < bytes.length) { if (bytes[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]) tmp = '' } else { tmp += '%' + bytes[i].toString(16) } i++ } return res + decodeUtf8Char(tmp) } function _asciiSlice (buf, start, end) { var bytes = buf.slice(start, end) var ret = '' for (var i = 0; i < bytes.length; i++) ret += String.fromCharCode(bytes[i]) return ret } function _binarySlice (buf, start, end) { return _asciiSlice(buf, start, end) } function _hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } // TODO: add test that modifying the new buffer slice will modify memory in the // original buffer! Use code from: // http://nodejs.org/api/buffer.html#buffer_buf_slice_start_end function BufferSlice (start, end) { var len = this.length start = clamp(start, len, 0) end = clamp(end, len, len) return augment(this.subarray(start, end)) // Uint8Array built-in method } function BufferReadUInt8 (offset, noAssert) { var buf = this if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < buf.length, 'Trying to read beyond buffer length') } if (offset >= buf.length) return return buf[offset] } function _readUInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) { return } else if (offset + 1 === len) { var dv = new xDataView(new xArrayBuffer(2)) dv.setUint8(0, buf[len - 1]) return dv.getUint16(0, littleEndian) } else { return buf._dataview.getUint16(offset, littleEndian) } } function BufferReadUInt16LE (offset, noAssert) { return _readUInt16(this, offset, true, noAssert) } function BufferReadUInt16BE (offset, noAssert) { return _readUInt16(this, offset, false, noAssert) } function _readUInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) { return } else if (offset + 3 >= len) { var dv = new xDataView(new xArrayBuffer(4)) for (var i = 0; i + offset < len; i++) { dv.setUint8(i, buf[i + offset]) } return dv.getUint32(0, littleEndian) } else { return buf._dataview.getUint32(offset, littleEndian) } } function BufferReadUInt32LE (offset, noAssert) { return _readUInt32(this, offset, true, noAssert) } function BufferReadUInt32BE (offset, noAssert) { return _readUInt32(this, offset, false, noAssert) } function BufferReadInt8 (offset, noAssert) { var buf = this if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < buf.length, 'Trying to read beyond buffer length') } if (offset >= buf.length) return return buf._dataview.getInt8(offset) } function _readInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) { return } else if (offset + 1 === len) { var dv = new xDataView(new xArrayBuffer(2)) dv.setUint8(0, buf[len - 1]) return dv.getInt16(0, littleEndian) } else { return buf._dataview.getInt16(offset, littleEndian) } } function BufferReadInt16LE (offset, noAssert) { return _readInt16(this, offset, true, noAssert) } function BufferReadInt16BE (offset, noAssert) { return _readInt16(this, offset, false, noAssert) } function _readInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) { return } else if (offset + 3 >= len) { var dv = new xDataView(new xArrayBuffer(4)) for (var i = 0; i + offset < len; i++) { dv.setUint8(i, buf[i + offset]) } return dv.getInt32(0, littleEndian) } else { return buf._dataview.getInt32(offset, littleEndian) } } function BufferReadInt32LE (offset, noAssert) { return _readInt32(this, offset, true, noAssert) } function BufferReadInt32BE (offset, noAssert) { return _readInt32(this, offset, false, noAssert) } function _readFloat (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } return buf._dataview.getFloat32(offset, littleEndian) } function BufferReadFloatLE (offset, noAssert) { return _readFloat(this, offset, true, noAssert) } function BufferReadFloatBE (offset, noAssert) { return _readFloat(this, offset, false, noAssert) } function _readDouble (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') } return buf._dataview.getFloat64(offset, littleEndian) } function BufferReadDoubleLE (offset, noAssert) { return _readDouble(this, offset, true, noAssert) } function BufferReadDoubleBE (offset, noAssert) { return _readDouble(this, offset, false, noAssert) } function BufferWriteUInt8 (value, offset, noAssert) { var buf = this if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xff) } if (offset >= buf.length) return buf[offset] = value } function _writeUInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffff) } var len = buf.length if (offset >= len) { return } else if (offset + 1 === len) { var dv = new xDataView(new xArrayBuffer(2)) dv.setUint16(0, value, littleEndian) buf[offset] = dv.getUint8(0) } else { buf._dataview.setUint16(offset, value, littleEndian) } } function BufferWriteUInt16LE (value, offset, noAssert) { _writeUInt16(this, value, offset, true, noAssert) } function BufferWriteUInt16BE (value, offset, noAssert) { _writeUInt16(this, value, offset, false, noAssert) } function _writeUInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffffffff) } var len = buf.length if (offset >= len) { return } else if (offset + 3 >= len) { var dv = new xDataView(new xArrayBuffer(4)) dv.setUint32(0, value, littleEndian) for (var i = 0; i + offset < len; i++) { buf[i + offset] = dv.getUint8(i) } } else { buf._dataview.setUint32(offset, value, littleEndian) } } function BufferWriteUInt32LE (value, offset, noAssert) { _writeUInt32(this, value, offset, true, noAssert) } function BufferWriteUInt32BE (value, offset, noAssert) { _writeUInt32(this, value, offset, false, noAssert) } function BufferWriteInt8 (value, offset, noAssert) { var buf = this if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7f, -0x80) } if (offset >= buf.length) return buf._dataview.setInt8(offset, value) } function _writeInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fff, -0x8000) } var len = buf.length if (offset >= len) { return } else if (offset + 1 === len) { var dv = new xDataView(new xArrayBuffer(2)) dv.setInt16(0, value, littleEndian) buf[offset] = dv.getUint8(0) } else { buf._dataview.setInt16(offset, value, littleEndian) } } function BufferWriteInt16LE (value, offset, noAssert) { _writeInt16(this, value, offset, true, noAssert) } function BufferWriteInt16BE (value, offset, noAssert) { _writeInt16(this, value, offset, false, noAssert) } function _writeInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fffffff, -0x80000000) } var len = buf.length if (offset >= len) { return } else if (offset + 3 >= len) { var dv = new xDataView(new xArrayBuffer(4)) dv.setInt32(0, value, littleEndian) for (var i = 0; i + offset < len; i++) { buf[i + offset] = dv.getUint8(i) } } else { buf._dataview.setInt32(offset, value, littleEndian) } } function BufferWriteInt32LE (value, offset, noAssert) { _writeInt32(this, value, offset, true, noAssert) } function BufferWriteInt32BE (value, offset, noAssert) { _writeInt32(this, value, offset, false, noAssert) } function _writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) } var len = buf.length if (offset >= len) { return } else if (offset + 3 >= len) { var dv = new xDataView(new xArrayBuffer(4)) dv.setFloat32(0, value, littleEndian) for (var i = 0; i + offset < len; i++) { buf[i + offset] = dv.getUint8(i) } } else { buf._dataview.setFloat32(offset, value, littleEndian) } } function BufferWriteFloatLE (value, offset, noAssert) { _writeFloat(this, value, offset, true, noAssert) } function BufferWriteFloatBE (value, offset, noAssert) { _writeFloat(this, value, offset, false, noAssert) } function _writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof (littleEndian) === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 7 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) } var len = buf.length if (offset >= len) { return } else if (offset + 7 >= len) { var dv = new xDataView(new xArrayBuffer(8)) dv.setFloat64(0, value, littleEndian) for (var i = 0; i + offset < len; i++) { buf[i + offset] = dv.getUint8(i) } } else { buf._dataview.setFloat64(offset, value, littleEndian) } } function BufferWriteDoubleLE (value, offset, noAssert) { _writeDouble(this, value, offset, true, noAssert) } function BufferWriteDoubleBE (value, offset, noAssert) { _writeDouble(this, value, offset, false, noAssert) } // fill(value, start=0, end=buffer.length) function BufferFill (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (typeof value === 'string') { value = value.charCodeAt(0) } if (typeof value !== 'number' || isNaN(value)) { throw new Error('value is not a number') } if (end < start) throw new Error('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) { throw new Error('start out of bounds') } if (end < 0 || end > this.length) { throw new Error('end out of bounds') } for (var i = start; i < end; i++) { this[i] = value } } function BufferInspect () { var out = [] var len = this.length for (var i = 0; i < len; i++) { out[i] = toHex(this[i]) if (i === exports.INSPECT_MAX_BYTES) { out[i + 1] = '...' break } } return '<Buffer ' + out.join(' ') + '>' } // Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. // Added in Node 0.12. function BufferToArrayBuffer () { return (new Buffer(this)).buffer } // HELPER FUNCTIONS // ================ function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } /** * Check to see if the browser supports augmenting a `Uint8Array` instance. * @return {boolean} */ function _browserSupport () { var arr = new xUint8Array(0) arr.foo = function () { return 42 } try { return (42 === arr.foo()) } catch (e) { return false } } /** * Class: ProxyBuffer * ================== * * Only used in Firefox, since Firefox does not allow augmenting "native" * objects (like Uint8Array instances) with new properties for some unknown * (probably silly) reason. So we'll use an ES6 Proxy (supported since * Firefox 18) to wrap the Uint8Array instance without actually adding any * properties to it. * * Instances of this "fake" Buffer class are the "target" of the * ES6 Proxy (see `augment` function). * * We couldn't just use the `Uint8Array` as the target of the `Proxy` because * Proxies have an important limitation on trapping the `toString` method. * `Object.prototype.toString.call(proxy)` gets called whenever something is * implicitly cast to a String. Unfortunately, with a `Proxy` this * unconditionally returns `Object.prototype.toString.call(target)` which would * always return "[object Uint8Array]" if we used the `Uint8Array` instance as * the target. And, remember, in Firefox we cannot redefine the `Uint8Array` * instance's `toString` method. * * So, we use this `ProxyBuffer` class as the proxy's "target". Since this class * has its own custom `toString` method, it will get called whenever `toString` * gets called, implicitly or explicitly, on the `Proxy` instance. * * We also have to define the Uint8Array methods `subarray` and `set` on * `ProxyBuffer` because if we didn't then `proxy.subarray(0)` would have its * `this` set to `proxy` (a `Proxy` instance) which throws an exception in * Firefox which expects it to be a `TypedArray` instance. */ function ProxyBuffer (arr) { this._arr = arr if (arr.byteLength !== 0) this._dataview = new xDataView(arr.buffer, arr.byteOffset, arr.byteLength) } ProxyBuffer.prototype.write = BufferWrite ProxyBuffer.prototype.toString = BufferToString ProxyBuffer.prototype.toLocaleString = BufferToString ProxyBuffer.prototype.toJSON = BufferToJSON ProxyBuffer.prototype.copy = BufferCopy ProxyBuffer.prototype.slice = BufferSlice ProxyBuffer.prototype.readUInt8 = BufferReadUInt8 ProxyBuffer.prototype.readUInt16LE = BufferReadUInt16LE ProxyBuffer.prototype.readUInt16BE = BufferReadUInt16BE ProxyBuffer.prototype.readUInt32LE = BufferReadUInt32LE ProxyBuffer.prototype.readUInt32BE = BufferReadUInt32BE ProxyBuffer.prototype.readInt8 = BufferReadInt8 ProxyBuffer.prototype.readInt16LE = BufferReadInt16LE ProxyBuffer.prototype.readInt16BE = BufferReadInt16BE ProxyBuffer.prototype.readInt32LE = BufferReadInt32LE ProxyBuffer.prototype.readInt32BE = BufferReadInt32BE ProxyBuffer.prototype.readFloatLE = BufferReadFloatLE ProxyBuffer.prototype.readFloatBE = BufferReadFloatBE ProxyBuffer.prototype.readDoubleLE = BufferReadDoubleLE ProxyBuffer.prototype.readDoubleBE = BufferReadDoubleBE ProxyBuffer.prototype.writeUInt8 = BufferWriteUInt8 ProxyBuffer.prototype.writeUInt16LE = BufferWriteUInt16LE ProxyBuffer.prototype.writeUInt16BE = BufferWriteUInt16BE ProxyBuffer.prototype.writeUInt32LE = BufferWriteUInt32LE ProxyBuffer.prototype.writeUInt32BE = BufferWriteUInt32BE ProxyBuffer.prototype.writeInt8 = BufferWriteInt8 ProxyBuffer.prototype.writeInt16LE = BufferWriteInt16LE ProxyBuffer.prototype.writeInt16BE = BufferWriteInt16BE ProxyBuffer.prototype.writeInt32LE = BufferWriteInt32LE ProxyBuffer.prototype.writeInt32BE = BufferWriteInt32BE ProxyBuffer.prototype.writeFloatLE = BufferWriteFloatLE ProxyBuffer.prototype.writeFloatBE = BufferWriteFloatBE ProxyBuffer.prototype.writeDoubleLE = BufferWriteDoubleLE ProxyBuffer.prototype.writeDoubleBE = BufferWriteDoubleBE ProxyBuffer.prototype.fill = BufferFill ProxyBuffer.prototype.inspect = BufferInspect ProxyBuffer.prototype.toArrayBuffer = BufferToArrayBuffer ProxyBuffer.prototype._isBuffer = true ProxyBuffer.prototype.subarray = function () { return this._arr.subarray.apply(this._arr, arguments) } ProxyBuffer.prototype.set = function () { return this._arr.set.apply(this._arr, arguments) } var ProxyHandler = { get: function (target, name) { if (name in target) return target[name] else return target._arr[name] }, set: function (target, name, value) { target._arr[name] = value } } function augment (arr) { if (browserSupport === undefined) { browserSupport = _browserSupport() } if (browserSupport) { // Augment the Uint8Array *instance* (not the class!) with Buffer methods arr.write = BufferWrite arr.toString = BufferToString arr.toLocaleString = BufferToString arr.toJSON = BufferToJSON arr.copy = BufferCopy arr.slice = BufferSlice arr.readUInt8 = BufferReadUInt8 arr.readUInt16LE = BufferReadUInt16LE arr.readUInt16BE = BufferReadUInt16BE arr.readUInt32LE = BufferReadUInt32LE arr.readUInt32BE = BufferReadUInt32BE arr.readInt8 = BufferReadInt8 arr.readInt16LE = BufferReadInt16LE arr.readInt16BE = BufferReadInt16BE arr.readInt32LE = BufferReadInt32LE arr.readInt32BE = BufferReadInt32BE arr.readFloatLE = BufferReadFloatLE arr.readFloatBE = BufferReadFloatBE arr.readDoubleLE = BufferReadDoubleLE arr.readDoubleBE = BufferReadDoubleBE arr.writeUInt8 = BufferWriteUInt8 arr.writeUInt16LE = BufferWriteUInt16LE arr.writeUInt16BE = BufferWriteUInt16BE arr.writeUInt32LE = BufferWriteUInt32LE arr.writeUInt32BE = BufferWriteUInt32BE arr.writeInt8 = BufferWriteInt8 arr.writeInt16LE = BufferWriteInt16LE arr.writeInt16BE = BufferWriteInt16BE arr.writeInt32LE = BufferWriteInt32LE arr.writeInt32BE = BufferWriteInt32BE arr.writeFloatLE = BufferWriteFloatLE arr.writeFloatBE = BufferWriteFloatBE arr.writeDoubleLE = BufferWriteDoubleLE arr.writeDoubleBE = BufferWriteDoubleBE arr.fill = BufferFill arr.inspect = BufferInspect arr.toArrayBuffer = BufferToArrayBuffer arr._isBuffer = true if (arr.byteLength !== 0) arr._dataview = new xDataView(arr.buffer, arr.byteOffset, arr.byteLength) return arr } else { // This is a browser that doesn't support augmenting the `Uint8Array` // instance (*ahem* Firefox) so use an ES6 `Proxy`. var proxyBuffer = new ProxyBuffer(arr) var proxy = new Proxy(proxyBuffer, ProxyHandler) proxyBuffer._proxy = proxy return proxy } } // slice(start, end) function clamp (index, len, defaultValue) { if (typeof index !== 'number') return defaultValue index = ~~index; // Coerce to integer. if (index >= len) return len if (index >= 0) return index index += len if (index >= 0) return index return 0 } function coerce (length) { // Coerce length to a number (possibly NaN), round up // in case it's fractional (e.g. 123.456) then do a // double negate to coerce a NaN to 0. Easy, right? length = ~~Math.ceil(+length) return length < 0 ? 0 : length } function isArrayIsh (subject) { return Array.isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) if (str.charCodeAt(i) <= 0x7F) byteArray.push(str.charCodeAt(i)) else { var h = encodeURIComponent(str.charAt(i)).substr(1).split('%') for (var j = 0; j < h.length; j++) byteArray.push(parseInt(h[j], 16)) } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function base64ToBytes (str) { return require('base64-js').toByteArray(str) } function blitBuffer (src, dst, offset, length) { var pos, i = 0 while (i < length) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] i++ } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } /* * We have to make sure that the value is a valid integer. This means that it * is non-negative. It has no fractional component and that it does not * exceed the maximum allowed value. * * value The number to check for validity * * max The maximum value */ function verifuint (value, max) { assert(typeof (value) == 'number', 'cannot write a non-number as a number') assert(value >= 0, 'specified a negative value for writing an unsigned value') assert(value <= max, 'value is larger than maximum value for type') assert(Math.floor(value) === value, 'value has a fractional component') } /* * A series of checks to make sure we actually have a signed 32-bit number */ function verifsint(value, max, min) { assert(typeof (value) == 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') assert(Math.floor(value) === value, 'value has a fractional component') } function verifIEEE754(value, max, min) { assert(typeof (value) == 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') } function assert (test, message) { if (!test) throw new Error(message || 'Failed assertion') } },{"base64-js":3,"typedarray":4}],"native-buffer-browserify":[function(require,module,exports){ module.exports=require('PcZj9L'); },{}],3:[function(require,module,exports){ (function (exports) { 'use strict'; var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function b64ToByteArray(b64) { var i, j, l, tmp, placeHolders, arr; if (b64.length % 4 > 0) { throw 'Invalid string. Length must be a multiple of 4'; } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice placeHolders = b64.indexOf('='); placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0; // base64 is 4/3 + up to two characters of the original data arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length; for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]); arr.push((tmp & 0xFF0000) >> 16); arr.push((tmp & 0xFF00) >> 8); arr.push(tmp & 0xFF); } if (placeHolders === 2) { tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4); arr.push(tmp & 0xFF); } else if (placeHolders === 1) { tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2); arr.push((tmp >> 8) & 0xFF); arr.push(tmp & 0xFF); } return arr; } function uint8ToBase64(uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length; function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; }; // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); output += tripletToBase64(temp); } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1]; output += lookup[temp >> 2]; output += lookup[(temp << 4) & 0x3F]; output += '=='; break; case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]); output += lookup[temp >> 10]; output += lookup[(temp >> 4) & 0x3F]; output += lookup[(temp << 2) & 0x3F]; output += '='; break; } return output; } module.exports.toByteArray = b64ToByteArray; module.exports.fromByteArray = uint8ToBase64; }()); },{}],4:[function(require,module,exports){ var undefined = (void 0); // Paranoia // Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to // create, and consume so much memory, that the browser appears frozen. var MAX_ARRAY_LENGTH = 1e5; // Approximations of internal ECMAScript conversion functions var ECMAScript = (function() { // Stash a copy in case other scripts modify these var opts = Object.prototype.toString, ophop = Object.prototype.hasOwnProperty; return { // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, HasProperty: function(o, p) { return p in o; }, HasOwnProperty: function(o, p) { return ophop.call(o, p); }, IsCallable: function(o) { return typeof o === 'function'; }, ToInt32: function(v) { return v >> 0; }, ToUint32: function(v) { return v >>> 0; } }; }()); // Snapshot intrinsics var LN2 = Math.LN2, abs = Math.abs, floor = Math.floor, log = Math.log, min = Math.min, pow = Math.pow, round = Math.round; // ES5: lock down object properties function configureProperties(obj) { if (getOwnPropertyNames && defineProperty) { var props = getOwnPropertyNames(obj), i; for (i = 0; i < props.length; i += 1) { defineProperty(obj, props[i], { value: obj[props[i]], writable: false, enumerable: false, configurable: false }); } } } // emulate ES5 getter/setter API using legacy APIs // http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx // (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but // note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) var defineProperty = Object.defineProperty || function(o, p, desc) { if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } return o; }; var getOwnPropertyNames = Object.getOwnPropertyNames || function getOwnPropertyNames(o) { if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); var props = [], p; for (p in o) { if (ECMAScript.HasOwnProperty(o, p)) { props.push(p); } } return props; }; // ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) // for index in 0 ... obj.length function makeArrayAccessors(obj) { if (!defineProperty) { return; } if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); function makeArrayAccessor(index) { defineProperty(obj, index, { 'get': function() { return obj._getter(index); }, 'set': function(v) { obj._setter(index, v); }, enumerable: true, configurable: false }); } var i; for (i = 0; i < obj.length; i += 1) { makeArrayAccessor(i); } } // Internal conversion functions: // pack<Type>() - take a number (interpreted as Type), output a byte array // unpack<Type>() - take a byte array, output a Type-like number function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } function packI8(n) { return [n & 0xff]; } function unpackI8(bytes) { return as_signed(bytes[0], 8); } function packU8(n) { return [n & 0xff]; } function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; function roundToEven(n) { var w = floor(n), f = n - w; if (f < 0.5) return w; if (f > 0.5) return w + 1; return w % 2 ? w + 1 : w; } // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = abs(v); if (v >= pow(2, 1 - bias)) { e = min(floor(log(v) / LN2), 1023); f = roundToEven(v / pow(2, e) * pow(2, fbits)); if (f / pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normalized e = e + bias; f = f - pow(2, fbits); } } else { // Denormalized e = 0; f = roundToEven(v / pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.substring(0, 8), 2)); str = str.substring(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.substring(0, 1), 2) ? -1 : 1; e = parseInt(str.substring(1, 1 + ebits), 2); f = parseInt(str.substring(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackF64(b) { return unpackIEEE754(b, 11, 52); } function packF64(v) { return packIEEE754(v, 11, 52); } function unpackF32(b) { return unpackIEEE754(b, 8, 23); } function packF32(v) { return packIEEE754(v, 8, 23); } // // 3 The ArrayBuffer Type // (function() { /** @constructor */ var ArrayBuffer = function ArrayBuffer(length) { length = ECMAScript.ToInt32(length); if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); this.byteLength = length; this._bytes = []; this._bytes.length = length; var i; for (i = 0; i < this.byteLength; i += 1) { this._bytes[i] = 0; } configureProperties(this); }; exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; // // 4 The ArrayBufferView Type // // NOTE: this constructor is not exported /** @constructor */ var ArrayBufferView = function ArrayBufferView() { //this.buffer = null; //this.byteOffset = 0; //this.byteLength = 0; }; // // 5 The Typed Array View Types // function makeConstructor(bytesPerElement, pack, unpack) { // Each TypedArray type requires a distinct constructor instance with // identical logic, which this produces. var ctor; ctor = function(buffer, byteOffset, length) { var array, sequence, i, s; if (!arguments.length || typeof arguments[0] === 'number') { // Constructor(unsigned long length) this.length = ECMAScript.ToInt32(arguments[0]); if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { // Constructor(TypedArray array) array = arguments[0]; this.length = array.length; this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; for (i = 0; i < this.length; i += 1) { this._setter(i, array._getter(i)); } } else if (typeof arguments[0] === 'object' && !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { // Constructor(sequence<type> array) sequence = arguments[0]; this.length = ECMAScript.ToUint32(sequence.length); this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; for (i = 0; i < this.length; i += 1) { s = sequence[i]; this._setter(i, Number(s)); } } else if (typeof arguments[0] === 'object' && (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { // Constructor(ArrayBuffer buffer, // optional unsigned long byteOffset, optional unsigned long length) this.buffer = buffer; this.byteOffset = ECMAScript.ToUint32(byteOffset); if (this.byteOffset > this.buffer.byteLength) { throw new RangeError("byteOffset out of range"); } if (this.byteOffset % this.BYTES_PER_ELEMENT) { // The given byteOffset must be a multiple of the element // size of the specific type, otherwise an exception is raised. throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); } if (arguments.length < 3) { this.byteLength = this.buffer.byteLength - this.byteOffset; if (this.byteLength % this.BYTES_PER_ELEMENT) { throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); } this.length = this.byteLength / this.BYTES_PER_ELEMENT; } else { this.length = ECMAScript.ToUint32(length); this.byteLength = this.length * this.BYTES_PER_ELEMENT; } if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); } } else { throw new TypeError("Unexpected argument type(s)"); } this.constructor = ctor; configureProperties(this); makeArrayAccessors(this); }; ctor.prototype = new ArrayBufferView(); ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; ctor.prototype._pack = pack; ctor.prototype._unpack = unpack; ctor.BYTES_PER_ELEMENT = bytesPerElement; // getter type (unsigned long index); ctor.prototype._getter = function(index) { if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); index = ECMAScript.ToUint32(index); if (index >= this.length) { return undefined; } var bytes = [], i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { bytes.push(this.buffer._bytes[o]); } return this._unpack(bytes); }; // NONSTANDARD: convenience alias for getter: type get(unsigned long index); ctor.prototype.get = ctor.prototype._getter; // setter void (unsigned long index, type value); ctor.prototype._setter = function(index, value) { if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); index = ECMAScript.ToUint32(index); if (index >= this.length) { return undefined; } var bytes = this._pack(value), i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { this.buffer._bytes[o] = bytes[i]; } }; // void set(TypedArray array, optional unsigned long offset); // void set(sequence<type> array, optional unsigned long offset); ctor.prototype.set = function(index, value) { if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); var array, sequence, offset, len, i, s, d, byteOffset, byteLength, tmp; if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { // void set(TypedArray array, optional unsigned long offset); array = arguments[0]; offset = ECMAScript.ToUint32(arguments[1]); if (offset + array.length > this.length) { throw new RangeError("Offset plus length of array is out of range"); } byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; byteLength = array.length * this.BYTES_PER_ELEMENT; if (array.buffer === this.buffer) { tmp = []; for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { tmp[i] = array.buffer._bytes[s]; } for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { this.buffer._bytes[d] = tmp[i]; } } else { for (i = 0, s = array.byteOffset, d = byteOffset; i < byteLength; i += 1, s += 1, d += 1) { this.buffer._bytes[d] = array.buffer._bytes[s]; } } } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { // void set(sequence<type> array, optional unsigned long offset); sequence = arguments[0]; len = ECMAScript.ToUint32(sequence.length); offset = ECMAScript.ToUint32(arguments[1]); if (offset + len > this.length) { throw new RangeError("Offset plus length of array is out of range"); } for (i = 0; i < len; i += 1) { s = sequence[i]; this._setter(offset + i, Number(s)); } } else { throw new TypeError("Unexpected argument type(s)"); } }; // TypedArray subarray(long begin, optional long end); ctor.prototype.subarray = function(start, end) { function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } start = ECMAScript.ToInt32(start); end = ECMAScript.ToInt32(end); if (arguments.length < 1) { start = 0; } if (arguments.length < 2) { end = this.length; } if (start < 0) { start = this.length + start; } if (end < 0) { end = this.length + end; } start = clamp(start, 0, this.length); end = clamp(end, 0, this.length); var len = end - start; if (len < 0) { len = 0; } return new this.constructor( this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); }; return ctor; } var Int8Array = makeConstructor(1, packI8, unpackI8); var Uint8Array = makeConstructor(1, packU8, unpackU8); var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); var Int16Array = makeConstructor(2, packI16, unpackI16); var Uint16Array = makeConstructor(2, packU16, unpackU16); var Int32Array = makeConstructor(4, packI32, unpackI32); var Uint32Array = makeConstructor(4, packU32, unpackU32); var Float32Array = makeConstructor(4, packF32, unpackF32); var Float64Array = makeConstructor(8, packF64, unpackF64); exports.Int8Array = exports.Int8Array || Int8Array; exports.Uint8Array = exports.Uint8Array || Uint8Array; exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray; exports.Int16Array = exports.Int16Array || Int16Array; exports.Uint16Array = exports.Uint16Array || Uint16Array; exports.Int32Array = exports.Int32Array || Int32Array; exports.Uint32Array = exports.Uint32Array || Uint32Array; exports.Float32Array = exports.Float32Array || Float32Array; exports.Float64Array = exports.Float64Array || Float64Array; }()); // // 6 The DataView View Type // (function() { function r(array, index) { return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; } var IS_BIG_ENDIAN = (function() { var u16array = new(exports.Uint16Array)([0x1234]), u8array = new(exports.Uint8Array)(u16array.buffer); return r(u8array, 0) === 0x12; }()); // Constructor(ArrayBuffer buffer, // optional unsigned long byteOffset, // optional unsigned long byteLength) /** @constructor */ var DataView = function DataView(buffer, byteOffset, byteLength) { if (arguments.length === 0) { buffer = new ArrayBuffer(0); } else if (!(buffer instanceof ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { throw new TypeError("TypeError"); } this.buffer = buffer || new ArrayBuffer(0); this.byteOffset = ECMAScript.ToUint32(byteOffset); if (this.byteOffset > this.buffer.byteLength) { throw new RangeError("byteOffset out of range"); } if (arguments.length < 3) { this.byteLength = this.buffer.byteLength - this.byteOffset; } else { this.byteLength = ECMAScript.ToUint32(byteLength); } if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); } configureProperties(this); }; function makeGetter(arrayType) { return function(byteOffset, littleEndian) { byteOffset = ECMAScript.ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { throw new RangeError("Array index out of range"); } byteOffset += this.byteOffset; var uint8Array = new Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), bytes = [], i; for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { bytes.push(r(uint8Array, i)); } if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { bytes.reverse(); } return r(new arrayType(new Uint8Array(bytes).buffer), 0); }; } DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); DataView.prototype.getInt8 = makeGetter(exports.Int8Array); DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); DataView.prototype.getInt16 = makeGetter(exports.Int16Array); DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); DataView.prototype.getInt32 = makeGetter(exports.Int32Array); DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); function makeSetter(arrayType) { return function(byteOffset, value, littleEndian) { byteOffset = ECMAScript.ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { throw new RangeError("Array index out of range"); } // Get bytes var typeArray = new arrayType([value]), byteArray = new Uint8Array(typeArray.buffer), bytes = [], i, byteView; for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { bytes.push(r(byteArray, i)); } // Flip if necessary if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { bytes.reverse(); } // Write them byteView = new Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); byteView.set(bytes); }; } DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); DataView.prototype.setInt8 = makeSetter(exports.Int8Array); DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); DataView.prototype.setInt16 = makeSetter(exports.Int16Array); DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); DataView.prototype.setInt32 = makeSetter(exports.Int32Array); DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); exports.DataView = exports.DataView || DataView; }()); },{}]},{},[]) ;;module.exports=require("native-buffer-browserify").Buffer },{}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { if (ev.source === window && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],3:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/..\\node_modules\\poly-decomp\\src\\Line.js",__dirname="/..\\node_modules\\poly-decomp\\src";var Scalar = require('./Scalar'); module.exports = Line; /** * Container for line-related functions * @class Line */ function Line(){}; /** * Compute the intersection between two lines. * @static * @method lineInt * @param {Array} l1 Line vector 1 * @param {Array} l2 Line vector 2 * @param {Number} precision Precision to use when checking if the lines are parallel * @return {Array} The intersection point. */ Line.lineInt = function(l1,l2,precision){ precision = precision || 0; var i = [0,0]; // point var a1, b1, c1, a2, b2, c2, det; // scalars a1 = l1[1][1] - l1[0][1]; b1 = l1[0][0] - l1[1][0]; c1 = a1 * l1[0][0] + b1 * l1[0][1]; a2 = l2[1][1] - l2[0][1]; b2 = l2[0][0] - l2[1][0]; c2 = a2 * l2[0][0] + b2 * l2[0][1]; det = a1 * b2 - a2*b1; if (!Scalar.eq(det, 0, precision)) { // lines are not parallel i[0] = (b2 * c1 - b1 * c2) / det; i[1] = (a1 * c2 - a2 * c1) / det; } return i; }; /** * Checks if two line segments intersects. * @method segmentsIntersect * @param {Array} p1 The start vertex of the first line segment. * @param {Array} p2 The end vertex of the first line segment. * @param {Array} q1 The start vertex of the second line segment. * @param {Array} q2 The end vertex of the second line segment. * @return {Boolean} True if the two line segments intersect */ Line.segmentsIntersect = function(p1, p2, q1, q2){ var dx = p2[0] - p1[0]; var dy = p2[1] - p1[1]; var da = q2[0] - q1[0]; var db = q2[1] - q1[1]; // segments are parallel if(da*dy - db*dx == 0) return false; var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx) var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy) return (s>=0 && s<=1 && t>=0 && t<=1); }; },{"./Scalar":6,"__browserify_Buffer":1,"__browserify_process":2}],4:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/..\\node_modules\\poly-decomp\\src\\Point.js",__dirname="/..\\node_modules\\poly-decomp\\src";module.exports = Point; /** * Point related functions * @class Point */ function Point(){}; /** * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. * @static * @method area * @param {Array} a * @param {Array} b * @param {Array} c * @return {Number} */ Point.area = function(a,b,c){ return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))); }; Point.left = function(a,b,c){ return Point.area(a,b,c) > 0; }; Point.leftOn = function(a,b,c) { return Point.area(a, b, c) >= 0; }; Point.right = function(a,b,c) { return Point.area(a, b, c) < 0; }; Point.rightOn = function(a,b,c) { return Point.area(a, b, c) <= 0; }; var tmpPoint1 = [], tmpPoint2 = []; /** * Check if three points are collinear * @method collinear * @param {Array} a * @param {Array} b * @param {Array} c * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. * @return {Boolean} */ Point.collinear = function(a,b,c,thresholdAngle) { if(!thresholdAngle) return Point.area(a, b, c) == 0; else { var ab = tmpPoint1, bc = tmpPoint2; ab[0] = b[0]-a[0]; ab[1] = b[1]-a[1]; bc[0] = c[0]-b[0]; bc[1] = c[1]-b[1]; var dot = ab[0]*bc[0] + ab[1]*bc[1], magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]), magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]), angle = Math.acos(dot/(magA*magB)); return angle < thresholdAngle; } }; Point.sqdist = function(a,b){ var dx = b[0] - a[0]; var dy = b[1] - a[1]; return dx * dx + dy * dy; }; },{"__browserify_Buffer":1,"__browserify_process":2}],5:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/..\\node_modules\\poly-decomp\\src\\Polygon.js",__dirname="/..\\node_modules\\poly-decomp\\src";var Line = require("./Line") , Point = require("./Point") , Scalar = require("./Scalar") module.exports = Polygon; /** * Polygon class. * @class Polygon * @constructor */ function Polygon(){ /** * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] * @property vertices * @type {Array} */ this.vertices = []; } /** * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. * @method at * @param {Number} i * @return {Array} */ Polygon.prototype.at = function(i){ var v = this.vertices, s = v.length; return v[i < 0 ? i % s + s : i % s]; }; /** * Get first vertex * @method first * @return {Array} */ Polygon.prototype.first = function(){ return this.vertices[0]; }; /** * Get last vertex * @method last * @return {Array} */ Polygon.prototype.last = function(){ return this.vertices[this.vertices.length-1]; }; /** * Clear the polygon data * @method clear * @return {Array} */ Polygon.prototype.clear = function(){ this.vertices.length = 0; }; /** * Append points "from" to "to"-1 from an other polygon "poly" onto this one. * @method append * @param {Polygon} poly The polygon to get points from. * @param {Number} from The vertex index in "poly". * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. * @return {Array} */ Polygon.prototype.append = function(poly,from,to){ if(typeof(from) == "undefined") throw new Error("From is not given!"); if(typeof(to) == "undefined") throw new Error("To is not given!"); if(to-1 < from) throw new Error("lol1"); if(to > poly.vertices.length) throw new Error("lol2"); if(from < 0) throw new Error("lol3"); for(var i=from; i<to; i++){ this.vertices.push(poly.vertices[i]); } }; /** * Make sure that the polygon vertices are ordered counter-clockwise. * @method makeCCW */ Polygon.prototype.makeCCW = function(){ var br = 0, v = this.vertices; // find bottom right point for (var i = 1; i < this.vertices.length; ++i) { if (v[i][1] < v[br][1] || (v[i][1] == v[br][1] && v[i][0] > v[br][0])) { br = i; } } // reverse poly if clockwise if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { this.reverse(); } }; /** * Reverse the vertices in the polygon * @method reverse */ Polygon.prototype.reverse = function(){ var tmp = []; for(var i=0, N=this.vertices.length; i!==N; i++){ tmp.push(this.vertices.pop()); } this.vertices = tmp; }; /** * Check if a point in the polygon is a reflex point * @method isReflex * @param {Number} i * @return {Boolean} */ Polygon.prototype.isReflex = function(i){ return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); }; var tmpLine1=[], tmpLine2=[]; /** * Check if two vertices in the polygon can see each other * @method canSee * @param {Number} a Vertex index 1 * @param {Number} b Vertex index 2 * @return {Boolean} */ Polygon.prototype.canSee = function(a,b) { var p, dist, l1=tmpLine1, l2=tmpLine2; if (Point.leftOn(this.at(a + 1), this.at(a), this.at(b)) && Point.rightOn(this.at(a - 1), this.at(a), this.at(b))) { return false; } dist = Point.sqdist(this.at(a), this.at(b)); for (var i = 0; i !== this.vertices.length; ++i) { // for each edge if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges continue; if (Point.leftOn(this.at(a), this.at(b), this.at(i + 1)) && Point.rightOn(this.at(a), this.at(b), this.at(i))) { // if diag intersects an edge l1[0] = this.at(a); l1[1] = this.at(b); l2[0] = this.at(i); l2[1] = this.at(i + 1); p = Line.lineInt(l1,l2); if (Point.sqdist(this.at(a), p) < dist) { // if edge is blocking visibility to b return false; } } } return true; }; /** * Copy the polygon from vertex i to vertex j. * @method copy * @param {Number} i * @param {Number} j * @param {Polygon} [targetPoly] Optional target polygon to save in. * @return {Polygon} The resulting copy. */ Polygon.prototype.copy = function(i,j,targetPoly){ var p = targetPoly || new Polygon(); p.clear(); if (i < j) { // Insert all vertices from i to j for(var k=i; k<=j; k++) p.vertices.push(this.vertices[k]); } else { // Insert vertices 0 to j for(var k=0; k<=j; k++) p.vertices.push(this.vertices[k]); // Insert vertices i to end for(var k=i; k<this.vertices.length; k++) p.vertices.push(this.vertices[k]); } return p; }; /** * Decomposes the polygon into convex pieces. Returns a list of edges [[p1,p2],[p2,p3],...] that cuts the polygon. * Note that this algorithm has complexity O(N^4) and will be very slow for polygons with many vertices. * @method getCutEdges * @return {Array} */ Polygon.prototype.getCutEdges = function() { var min=[], tmp1=[], tmp2=[], tmpPoly = new Polygon(); var nDiags = Number.MAX_VALUE; for (var i = 0; i < this.vertices.length; ++i) { if (this.isReflex(i)) { for (var j = 0; j < this.vertices.length; ++j) { if (this.canSee(i, j)) { tmp1 = this.copy(i, j, tmpPoly).getCutEdges(); tmp2 = this.copy(j, i, tmpPoly).getCutEdges(); for(var k=0; k<tmp2.length; k++) tmp1.push(tmp2[k]); if (tmp1.length < nDiags) { min = tmp1; nDiags = tmp1.length; min.push([this.at(i), this.at(j)]); } } } } } return min; }; /** * Decomposes the polygon into one or more convex sub-Polygons. * @method decomp * @return {Array} An array or Polygon objects. */ Polygon.prototype.decomp = function(){ var edges = this.getCutEdges(); if(edges.length > 0) return this.slice(edges); else return [this]; }; /** * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. * @method slice * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() * @return {Array} */ Polygon.prototype.slice = function(cutEdges){ if(cutEdges.length == 0) return [this]; if(cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length==2 && cutEdges[0][0] instanceof Array){ var polys = [this]; for(var i=0; i<cutEdges.length; i++){ var cutEdge = cutEdges[i]; // Cut all polys for(var j=0; j<polys.length; j++){ var poly = polys[j]; var result = poly.slice(cutEdge); if(result){ // Found poly! Cut and quit polys.splice(j,1); polys.push(result[0],result[1]); break; } } } return polys; } else { // Was given one edge var cutEdge = cutEdges; var i = this.vertices.indexOf(cutEdge[0]); var j = this.vertices.indexOf(cutEdge[1]); if(i != -1 && j != -1){ return [this.copy(i,j), this.copy(j,i)]; } else { return false; } } }; /** * Checks that the line segments of this polygon do not intersect each other. * @method isSimple * @param {Array} path An array of vertices e.g. [[0,0],[0,1],...] * @return {Boolean} * @todo Should it check all segments with all others? */ Polygon.prototype.isSimple = function(){ var path = this.vertices; // Check for(var i=0; i<path.length-1; i++){ for(var j=0; j<i-1; j++){ if(Line.segmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){ return false; } } } // Check the segment between the last and the first point to all others for(var i=1; i<path.length-2; i++){ if(Line.segmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){ return false; } } return true; }; function getIntersectionPoint(p1, p2, q1, q2, delta){ delta = delta || 0; var a1 = p2[1] - p1[1]; var b1 = p1[0] - p2[0]; var c1 = (a1 * p1[0]) + (b1 * p1[1]); var a2 = q2[1] - q1[1]; var b2 = q1[0] - q2[0]; var c2 = (a2 * q1[0]) + (b2 * q1[1]); var det = (a1 * b2) - (a2 * b1); if(!Scalar.eq(det,0,delta)) return [((b2 * c1) - (b1 * c2)) / det, ((a1 * c2) - (a2 * c1)) / det] else return [0,0] } /** * Quickly decompose the Polygon into convex sub-polygons. * @method quickDecomp * @param {Array} result * @param {Array} [reflexVertices] * @param {Array} [steinerPoints] * @param {Number} [delta] * @param {Number} [maxlevel] * @param {Number} [level] * @return {Array} */ Polygon.prototype.quickDecomp = function(result,reflexVertices,steinerPoints,delta,maxlevel,level){ maxlevel = maxlevel || 100; level = level || 0; delta = delta || 25; result = typeof(result)!="undefined" ? result : []; reflexVertices = reflexVertices || []; steinerPoints = steinerPoints || []; var upperInt=[0,0], lowerInt=[0,0], p=[0,0]; // Points var upperDist=0, lowerDist=0, d=0, closestDist=0; // scalars var upperIndex=0, lowerIndex=0, closestIndex=0; // Integers var lowerPoly=new Polygon(), upperPoly=new Polygon(); // polygons var poly = this, v = this.vertices; if(v.length < 3) return result; level++; if(level > maxlevel){ console.warn("quickDecomp: max level ("+maxlevel+") reached."); return result; } for (var i = 0; i < this.vertices.length; ++i) { if (poly.isReflex(i)) { reflexVertices.push(poly.vertices[i]); upperDist = lowerDist = Number.MAX_VALUE; for (var j = 0; j < this.vertices.length; ++j) { if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly d = Point.sqdist(poly.vertices[i], p); if (d < lowerDist) { // keep only the closest intersection lowerDist = d; lowerInt = p; lowerIndex = j; } } } if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); if (Point.left(poly.at(i - 1), poly.at(i), p)) { d = Point.sqdist(poly.vertices[i], p); if (d < upperDist) { upperDist = d; upperInt = p; upperIndex = j; } } } } // if there are no vertices to connect to, choose a point in the middle if (lowerIndex == (upperIndex + 1) % this.vertices.length) { //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); p[0] = (lowerInt[0] + upperInt[0]) / 2; p[1] = (lowerInt[1] + upperInt[1]) / 2; steinerPoints.push(p); if (i < upperIndex) { //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); lowerPoly.append(poly, i, upperIndex+1); lowerPoly.vertices.push(p); upperPoly.vertices.push(p); if (lowerIndex != 0){ //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); upperPoly.append(poly,lowerIndex,poly.vertices.length); } //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); upperPoly.append(poly,0,i+1); } else { if (i != 0){ //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); lowerPoly.append(poly,i,poly.vertices.length); } //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); lowerPoly.append(poly,0,upperIndex+1); lowerPoly.vertices.push(p); upperPoly.vertices.push(p); //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); upperPoly.append(poly,lowerIndex,i+1); } } else { // connect to the closest point within the triangle //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); if (lowerIndex > upperIndex) { upperIndex += this.vertices.length; } closestDist = Number.MAX_VALUE; if(upperIndex < lowerIndex){ return result; } for (var j = lowerIndex; j <= upperIndex; ++j) { if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { d = Point.sqdist(poly.at(i), poly.at(j)); if (d < closestDist) { closestDist = d; closestIndex = j % this.vertices.length; } } } if (i < closestIndex) { lowerPoly.append(poly,i,closestIndex+1); if (closestIndex != 0){ upperPoly.append(poly,closestIndex,v.length); } upperPoly.append(poly,0,i+1); } else { if (i != 0){ lowerPoly.append(poly,i,v.length); } lowerPoly.append(poly,0,closestIndex+1); upperPoly.append(poly,closestIndex,i+1); } } // solve smallest poly first if (lowerPoly.vertices.length < upperPoly.vertices.length) { lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); } else { upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); } return result; } } result.push(this); return result; }; /** * Remove collinear points in the polygon. * @method removeCollinearPoints * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. * @return {Number} The number of points removed */ Polygon.prototype.removeCollinearPoints = function(precision){ var num = 0; for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ // Remove the middle point this.vertices.splice(i%this.vertices.length,1); i--; // Jump one point forward. Otherwise we may get a chain removal num++; } } return num; }; },{"./Line":3,"./Point":4,"./Scalar":6,"__browserify_Buffer":1,"__browserify_process":2}],6:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/..\\node_modules\\poly-decomp\\src\\Scalar.js",__dirname="/..\\node_modules\\poly-decomp\\src";module.exports = Scalar; /** * Scalar functions * @class Scalar */ function Scalar(){} /** * Check if two scalars are equal * @static * @method eq * @param {Number} a * @param {Number} b * @param {Number} [precision] * @return {Boolean} */ Scalar.eq = function(a,b,precision){ precision = precision || 0; return Math.abs(a-b) < precision; }; },{"__browserify_Buffer":1,"__browserify_process":2}],7:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/..\\node_modules\\poly-decomp\\src\\index.js",__dirname="/..\\node_modules\\poly-decomp\\src";module.exports = { Polygon : require("./Polygon"), Point : require("./Point"), }; },{"./Point":4,"./Polygon":5,"__browserify_Buffer":1,"__browserify_process":2}],8:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/..\\package.json",__dirname="/..";module.exports={ "name": "p2", "version": "0.6.0", "description": "A JavaScript 2D physics engine.", "author": "Stefan Hedman <[email protected]> (http://steffe.se)", "keywords": [ "p2.js", "p2", "physics", "engine", "2d" ], "main": "./src/p2.js", "engines": { "node": "*" }, "repository": { "type": "git", "url": "https://github.com/schteppe/p2.js.git" }, "bugs": { "url": "https://github.com/schteppe/p2.js/issues" }, "licenses": [ { "type": "MIT" } ], "devDependencies": { "grunt": "~0.4.0", "grunt-contrib-jshint": "~0.9.2", "grunt-contrib-nodeunit": "~0.1.2", "grunt-contrib-uglify": "~0.4.0", "grunt-contrib-watch": "~0.5.0", "grunt-browserify": "~2.0.1", "grunt-contrib-concat": "^0.4.0" }, "dependencies": { "poly-decomp": "0.1.0" } } },{"__browserify_Buffer":1,"__browserify_process":2}],9:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/collision\\AABB.js",__dirname="/collision";var vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = AABB; /** * Axis aligned bounding box class. * @class AABB * @constructor * @param {Object} [options] * @param {Array} [options.upperBound] * @param {Array} [options.lowerBound] */ function AABB(options){ /** * The lower bound of the bounding box. * @property lowerBound * @type {Array} */ this.lowerBound = vec2.create(); if(options && options.lowerBound){ vec2.copy(this.lowerBound, options.lowerBound); } /** * The upper bound of the bounding box. * @property upperBound * @type {Array} */ this.upperBound = vec2.create(); if(options && options.upperBound){ vec2.copy(this.upperBound, options.upperBound); } } var tmp = vec2.create(); /** * Set the AABB bounds from a set of points. * @method setFromPoints * @param {Array} points An array of vec2's. */ AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ var l = this.lowerBound, u = this.upperBound; if(typeof(angle) !== "number"){ angle = 0; } // Set to the first point if(angle !== 0){ vec2.rotate(l, points[0], angle); } else { vec2.copy(l, points[0]); } vec2.copy(u, l); // Compute cosines and sines just once var cosAngle = Math.cos(angle), sinAngle = Math.sin(angle); for(var i = 1; i<points.length; i++){ var p = points[i]; if(angle !== 0){ var x = p[0], y = p[1]; tmp[0] = cosAngle * x -sinAngle * y; tmp[1] = sinAngle * x +cosAngle * y; p = tmp; } for(var j=0; j<2; j++){ if(p[j] > u[j]){ u[j] = p[j]; } if(p[j] < l[j]){ l[j] = p[j]; } } } // Add offset if(position){ vec2.add(this.lowerBound, this.lowerBound, position); vec2.add(this.upperBound, this.upperBound, position); } if(skinSize){ this.lowerBound[0] -= skinSize; this.lowerBound[1] -= skinSize; this.upperBound[0] += skinSize; this.upperBound[1] += skinSize; } }; /** * Copy bounds from an AABB to this AABB * @method copy * @param {AABB} aabb */ AABB.prototype.copy = function(aabb){ vec2.copy(this.lowerBound, aabb.lowerBound); vec2.copy(this.upperBound, aabb.upperBound); }; /** * Extend this AABB so that it covers the given AABB too. * @method extend * @param {AABB} aabb */ AABB.prototype.extend = function(aabb){ // Loop over x and y var i = 2; while(i--){ // Extend lower bound var l = aabb.lowerBound[i]; if(this.lowerBound[i] > l){ this.lowerBound[i] = l; } // Upper var u = aabb.upperBound[i]; if(this.upperBound[i] < u){ this.upperBound[i] = u; } } }; /** * Returns true if the given AABB overlaps this AABB. * @method overlaps * @param {AABB} aabb * @return {Boolean} */ AABB.prototype.overlaps = function(aabb){ var l1 = this.lowerBound, u1 = this.upperBound, l2 = aabb.lowerBound, u2 = aabb.upperBound; // l2 u2 // |---------| // |--------| // l1 u1 return ((l2[0] <= u1[0] && u1[0] <= u2[0]) || (l1[0] <= u2[0] && u2[0] <= u1[0])) && ((l2[1] <= u1[1] && u1[1] <= u2[1]) || (l1[1] <= u2[1] && u2[1] <= u1[1])); }; },{"../math/vec2":31,"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],10:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/collision\\Broadphase.js",__dirname="/collision";var vec2 = require('../math/vec2'); var Body = require('../objects/Body'); module.exports = Broadphase; /** * Base class for broadphase implementations. * @class Broadphase * @constructor */ function Broadphase(type){ this.type = type; /** * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). * @property result * @type {Array} */ this.result = []; /** * The world to search for collision pairs in. To change it, use .setWorld() * @property world * @type {World} * @readOnly */ this.world = null; /** * The bounding volume type to use in the broadphase algorithms. * @property {Number} boundingVolumeType */ this.boundingVolumeType = Broadphase.AABB; } /** * Axis aligned bounding box type. * @static * @property {Number} AABB */ Broadphase.AABB = 1; /** * Bounding circle type. * @static * @property {Number} BOUNDING_CIRCLE */ Broadphase.BOUNDING_CIRCLE = 2; /** * Set the world that we are searching for collision pairs in * @method setWorld * @param {World} world */ Broadphase.prototype.setWorld = function(world){ this.world = world; }; /** * Get all potential intersecting body pairs. * @method getCollisionPairs * @param {World} world The world to search in. * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). */ Broadphase.prototype.getCollisionPairs = function(world){ throw new Error("getCollisionPairs must be implemented in a subclass!"); }; var dist = vec2.create(); /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.boundingRadiusCheck = function(bodyA, bodyB){ vec2.sub(dist, bodyA.position, bodyB.position); var d2 = vec2.squaredLength(dist), r = bodyA.boundingRadius + bodyB.boundingRadius; return d2 <= r*r; }; /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.aabbCheck = function(bodyA, bodyB){ return bodyA.getAABB().overlaps(bodyB.getAABB()); }; /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.prototype.boundingVolumeCheck = function(bodyA, bodyB){ var result; switch(this.boundingVolumeType){ case Broadphase.BOUNDING_CIRCLE: result = Broadphase.boundingRadiusCheck(bodyA,bodyB); break; case Broadphase.AABB: result = Broadphase.aabbCheck(bodyA,bodyB); break; default: throw new Error('Bounding volume type not recognized: '+this.boundingVolumeType); } return result; }; /** * Check whether two bodies are allowed to collide at all. * @method canCollide * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.canCollide = function(bodyA, bodyB){ // Cannot collide static bodies if(bodyA.type === Body.STATIC && bodyB.type === Body.STATIC){ return false; } // Cannot collide static vs kinematic bodies if( (bodyA.type === Body.KINEMATIC && bodyB.type === Body.STATIC) || (bodyA.type === Body.STATIC && bodyB.type === Body.KINEMATIC)){ return false; } // Cannot collide kinematic vs kinematic if(bodyA.type === Body.KINEMATIC && bodyB.type === Body.KINEMATIC){ return false; } // Cannot collide both sleeping bodies if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ return false; } // Cannot collide if one is static and the other is sleeping if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === Body.STATIC) || (bodyB.sleepState === Body.SLEEPING && bodyA.type === Body.STATIC)){ return false; } return true; }; Broadphase.NAIVE = 1; Broadphase.SAP = 2; },{"../math/vec2":31,"../objects/Body":32,"__browserify_Buffer":1,"__browserify_process":2}],11:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/collision\\GridBroadphase.js",__dirname="/collision";var Circle = require('../shapes/Circle') , Plane = require('../shapes/Plane') , Particle = require('../shapes/Particle') , Broadphase = require('../collision/Broadphase') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = GridBroadphase; /** * Broadphase that uses axis-aligned bins. * @class GridBroadphase * @constructor * @extends Broadphase * @param {object} [options] * @param {number} [options.xmin] Lower x bound of the grid * @param {number} [options.xmax] Upper x bound * @param {number} [options.ymin] Lower y bound * @param {number} [options.ymax] Upper y bound * @param {number} [options.nx] Number of bins along x axis * @param {number} [options.ny] Number of bins along y axis * @todo Should have an option for dynamic scene size */ function GridBroadphase(options){ Broadphase.apply(this); options = Utils.defaults(options,{ xmin: -100, xmax: 100, ymin: -100, ymax: 100, nx: 10, ny: 10 }); this.xmin = options.xmin; this.ymin = options.ymin; this.xmax = options.xmax; this.ymax = options.ymax; this.nx = options.nx; this.ny = options.ny; this.binsizeX = (this.xmax-this.xmin) / this.nx; this.binsizeY = (this.ymax-this.ymin) / this.ny; } GridBroadphase.prototype = new Broadphase(); /** * Get collision pairs. * @method getCollisionPairs * @param {World} world * @return {Array} */ GridBroadphase.prototype.getCollisionPairs = function(world){ var result = [], bodies = world.bodies, Ncolliding = bodies.length, binsizeX = this.binsizeX, binsizeY = this.binsizeY, nx = this.nx, ny = this.ny, xmin = this.xmin, ymin = this.ymin, xmax = this.xmax, ymax = this.ymax; // Todo: make garbage free var bins=[], Nbins=nx*ny; for(var i=0; i<Nbins; i++){ bins.push([]); } var xmult = nx / (xmax-xmin); var ymult = ny / (ymax-ymin); // Put all bodies into bins for(var i=0; i!==Ncolliding; i++){ var bi = bodies[i]; var aabb = bi.aabb; var lowerX = Math.max(aabb.lowerBound[0], xmin); var lowerY = Math.max(aabb.lowerBound[1], ymin); var upperX = Math.min(aabb.upperBound[0], xmax); var upperY = Math.min(aabb.upperBound[1], ymax); var xi1 = Math.floor(xmult * (lowerX - xmin)); var yi1 = Math.floor(ymult * (lowerY - ymin)); var xi2 = Math.floor(xmult * (upperX - xmin)); var yi2 = Math.floor(ymult * (upperY - ymin)); // Put in bin for(var j=xi1; j<=xi2; j++){ for(var k=yi1; k<=yi2; k++){ var xi = j; var yi = k; var idx = xi*(ny-1) + yi; if(idx >= 0 && idx < Nbins){ bins[ idx ].push(bi); } } } } // Check each bin for(var i=0; i!==Nbins; i++){ var bin = bins[i]; for(var j=0, NbodiesInBin=bin.length; j!==NbodiesInBin; j++){ var bi = bin[j]; for(var k=0; k!==j; k++){ var bj = bin[k]; if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } } return result; }; },{"../collision/Broadphase":10,"../math/vec2":31,"../shapes/Circle":38,"../shapes/Particle":42,"../shapes/Plane":43,"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],12:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/collision\\NaiveBroadphase.js",__dirname="/collision";var Circle = require('../shapes/Circle'), Plane = require('../shapes/Plane'), Shape = require('../shapes/Shape'), Particle = require('../shapes/Particle'), Broadphase = require('../collision/Broadphase'), vec2 = require('../math/vec2'); module.exports = NaiveBroadphase; /** * Naive broadphase implementation. Does N^2 tests. * * @class NaiveBroadphase * @constructor * @extends Broadphase */ function NaiveBroadphase(){ Broadphase.call(this, Broadphase.NAIVE); } NaiveBroadphase.prototype = new Broadphase(); /** * Get the colliding pairs * @method getCollisionPairs * @param {World} world * @return {Array} */ NaiveBroadphase.prototype.getCollisionPairs = function(world){ var bodies = world.bodies, result = this.result; result.length = 0; for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ var bi = bodies[i]; for(var j=0; j<i; j++){ var bj = bodies[j]; if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } return result; }; },{"../collision/Broadphase":10,"../math/vec2":31,"../shapes/Circle":38,"../shapes/Particle":42,"../shapes/Plane":43,"../shapes/Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],13:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/collision\\Narrowphase.js",__dirname="/collision";var vec2 = require('../math/vec2') , sub = vec2.sub , add = vec2.add , dot = vec2.dot , Utils = require('../utils/Utils') , TupleDictionary = require('../utils/TupleDictionary') , Equation = require('../equations/Equation') , ContactEquation = require('../equations/ContactEquation') , FrictionEquation = require('../equations/FrictionEquation') , Circle = require('../shapes/Circle') , Convex = require('../shapes/Convex') , Shape = require('../shapes/Shape') , Body = require('../objects/Body') , Rectangle = require('../shapes/Rectangle'); module.exports = Narrowphase; // Temp things var yAxis = vec2.fromValues(0,1); var tmp1 = vec2.fromValues(0,0) , tmp2 = vec2.fromValues(0,0) , tmp3 = vec2.fromValues(0,0) , tmp4 = vec2.fromValues(0,0) , tmp5 = vec2.fromValues(0,0) , tmp6 = vec2.fromValues(0,0) , tmp7 = vec2.fromValues(0,0) , tmp8 = vec2.fromValues(0,0) , tmp9 = vec2.fromValues(0,0) , tmp10 = vec2.fromValues(0,0) , tmp11 = vec2.fromValues(0,0) , tmp12 = vec2.fromValues(0,0) , tmp13 = vec2.fromValues(0,0) , tmp14 = vec2.fromValues(0,0) , tmp15 = vec2.fromValues(0,0) , tmp16 = vec2.fromValues(0,0) , tmp17 = vec2.fromValues(0,0) , tmp18 = vec2.fromValues(0,0) , tmpArray = []; /** * Narrowphase. Creates contacts and friction given shapes and transforms. * @class Narrowphase * @constructor */ function Narrowphase(){ /** * @property contactEquations * @type {Array} */ this.contactEquations = []; /** * @property frictionEquations * @type {Array} */ this.frictionEquations = []; /** * Whether to make friction equations in the upcoming contacts. * @property enableFriction * @type {Boolean} */ this.enableFriction = true; /** * The friction slip force to use when creating friction equations. * @property slipForce * @type {Number} */ this.slipForce = 10.0; /** * The friction value to use in the upcoming friction equations. * @property frictionCoefficient * @type {Number} */ this.frictionCoefficient = 0.3; /** * Will be the .relativeVelocity in each produced FrictionEquation. * @property {Number} surfaceVelocity */ this.surfaceVelocity = 0; this.reuseObjects = true; this.reusableContactEquations = []; this.reusableFrictionEquations = []; /** * The restitution value to use in the next contact equations. * @property restitution * @type {Number} */ this.restitution = 0; /** * The stiffness value to use in the next contact equations. * @property {Number} stiffness */ this.stiffness = Equation.DEFAULT_STIFFNESS; /** * The stiffness value to use in the next contact equations. * @property {Number} stiffness */ this.relaxation = Equation.DEFAULT_RELAXATION; /** * The stiffness value to use in the next friction equations. * @property frictionStiffness * @type {Number} */ this.frictionStiffness = Equation.DEFAULT_STIFFNESS; /** * The relaxation value to use in the next friction equations. * @property frictionRelaxation * @type {Number} */ this.frictionRelaxation = Equation.DEFAULT_RELAXATION; /** * Enable reduction of friction equations. If disabled, a box on a plane will generate 2 contact equations and 2 friction equations. If enabled, there will be only one friction equation. Same kind of simplifications are made for all collision types. * @property enableFrictionReduction * @type {Boolean} * @deprecated This flag will be removed when the feature is stable enough. * @default true */ this.enableFrictionReduction = true; /** * Keeps track of the colliding bodies last step. * @private * @property collidingBodiesLastStep * @type {TupleDictionary} */ this.collidingBodiesLastStep = new TupleDictionary(); /** * Contact skin size value to use in the next contact equations. * @property {Number} contactSkinSize * @default 0.01 */ this.contactSkinSize = 0.01; } /** * Check if the bodies were in contact since the last reset(). * @method collidedLastStep * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Narrowphase.prototype.collidedLastStep = function(bodyA, bodyB){ var id1 = bodyA.id|0, id2 = bodyB.id|0; return !!this.collidingBodiesLastStep.get(id1, id2); }; /** * Throws away the old equations and gets ready to create new * @method reset */ Narrowphase.prototype.reset = function(){ this.collidingBodiesLastStep.reset(); var eqs = this.contactEquations; var l = eqs.length; while(l--){ var eq = eqs[l], id1 = eq.bodyA.id, id2 = eq.bodyB.id; this.collidingBodiesLastStep.set(id1, id2, true); } if(this.reuseObjects){ var ce = this.contactEquations, fe = this.frictionEquations, rfe = this.reusableFrictionEquations, rce = this.reusableContactEquations; Utils.appendArray(rce,ce); Utils.appendArray(rfe,fe); } // Reset this.contactEquations.length = this.frictionEquations.length = 0; }; /** * Creates a ContactEquation, either by reusing an existing object or creating a new one. * @method createContactEquation * @param {Body} bodyA * @param {Body} bodyB * @return {ContactEquation} */ Narrowphase.prototype.createContactEquation = function(bodyA, bodyB, shapeA, shapeB){ var c = this.reusableContactEquations.length ? this.reusableContactEquations.pop() : new ContactEquation(bodyA,bodyB); c.bodyA = bodyA; c.bodyB = bodyB; c.shapeA = shapeA; c.shapeB = shapeB; c.restitution = this.restitution; c.firstImpact = !this.collidedLastStep(bodyA,bodyB); c.stiffness = this.stiffness; c.relaxation = this.relaxation; c.needsUpdate = true; c.enabled = true; c.offset = this.contactSkinSize; return c; }; /** * Creates a FrictionEquation, either by reusing an existing object or creating a new one. * @method createFrictionEquation * @param {Body} bodyA * @param {Body} bodyB * @return {FrictionEquation} */ Narrowphase.prototype.createFrictionEquation = function(bodyA, bodyB, shapeA, shapeB){ var c = this.reusableFrictionEquations.length ? this.reusableFrictionEquations.pop() : new FrictionEquation(bodyA,bodyB); c.bodyA = bodyA; c.bodyB = bodyB; c.shapeA = shapeA; c.shapeB = shapeB; c.setSlipForce(this.slipForce); c.frictionCoefficient = this.frictionCoefficient; c.relativeVelocity = this.surfaceVelocity; c.enabled = true; c.needsUpdate = true; c.stiffness = this.frictionStiffness; c.relaxation = this.frictionRelaxation; c.contactEquations.length = 0; return c; }; /** * Creates a FrictionEquation given the data in the ContactEquation. Uses same offset vectors ri and rj, but the tangent vector will be constructed from the collision normal. * @method createFrictionFromContact * @param {ContactEquation} contactEquation * @return {FrictionEquation} */ Narrowphase.prototype.createFrictionFromContact = function(c){ var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB); vec2.copy(eq.contactPointA, c.contactPointA); vec2.copy(eq.contactPointB, c.contactPointB); vec2.rotate90cw(eq.t, c.normalA); eq.contactEquations.push(c); return eq; }; // Take the average N latest contact point on the plane. Narrowphase.prototype.createFrictionFromAverage = function(numContacts){ if(!numContacts){ throw new Error("numContacts == 0!"); } var c = this.contactEquations[this.contactEquations.length - 1]; var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB); var bodyA = c.bodyA; var bodyB = c.bodyB; vec2.set(eq.contactPointA, 0, 0); vec2.set(eq.contactPointB, 0, 0); vec2.set(eq.t, 0, 0); for(var i=0; i!==numContacts; i++){ c = this.contactEquations[this.contactEquations.length - 1 - i]; if(c.bodyA === bodyA){ vec2.add(eq.t, eq.t, c.normalA); vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA); vec2.add(eq.contactPointB, eq.contactPointB, c.contactPointB); } else { vec2.sub(eq.t, eq.t, c.normalA); vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointB); vec2.add(eq.contactPointB, eq.contactPointB, c.contactPointA); } eq.contactEquations.push(c); } var invNumContacts = 1/numContacts; vec2.scale(eq.contactPointA, eq.contactPointA, invNumContacts); vec2.scale(eq.contactPointB, eq.contactPointB, invNumContacts); vec2.normalize(eq.t, eq.t); vec2.rotate90cw(eq.t, eq.t); return eq; }; /** * Convex/line narrowphase * @method convexLine * @param {Body} convexBody * @param {Convex} convexShape * @param {Array} convexOffset * @param {Number} convexAngle * @param {Body} lineBody * @param {Line} lineShape * @param {Array} lineOffset * @param {Number} lineAngle * @param {boolean} justTest * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.CONVEX] = Narrowphase.prototype.convexLine = function( convexBody, convexShape, convexOffset, convexAngle, lineBody, lineShape, lineOffset, lineAngle, justTest ){ // TODO if(justTest){ return false; } else { return 0; } }; /** * Line/rectangle narrowphase * @method lineRectangle * @param {Body} lineBody * @param {Line} lineShape * @param {Array} lineOffset * @param {Number} lineAngle * @param {Body} rectangleBody * @param {Rectangle} rectangleShape * @param {Array} rectangleOffset * @param {Number} rectangleAngle * @param {Boolean} justTest * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.RECTANGLE] = Narrowphase.prototype.lineRectangle = function( lineBody, lineShape, lineOffset, lineAngle, rectangleBody, rectangleShape, rectangleOffset, rectangleAngle, justTest ){ // TODO if(justTest){ return false; } else { return 0; } }; function setConvexToCapsuleShapeMiddle(convexShape, capsuleShape){ vec2.set(convexShape.vertices[0], -capsuleShape.length * 0.5, -capsuleShape.radius); vec2.set(convexShape.vertices[1], capsuleShape.length * 0.5, -capsuleShape.radius); vec2.set(convexShape.vertices[2], capsuleShape.length * 0.5, capsuleShape.radius); vec2.set(convexShape.vertices[3], -capsuleShape.length * 0.5, capsuleShape.radius); } var convexCapsule_tempRect = new Rectangle(1,1), convexCapsule_tempVec = vec2.create(); /** * Convex/capsule narrowphase * @method convexCapsule * @param {Body} convexBody * @param {Convex} convexShape * @param {Array} convexPosition * @param {Number} convexAngle * @param {Body} capsuleBody * @param {Capsule} capsuleShape * @param {Array} capsulePosition * @param {Number} capsuleAngle */ Narrowphase.prototype[Shape.CAPSULE | Shape.CONVEX] = Narrowphase.prototype[Shape.CAPSULE | Shape.RECTANGLE] = Narrowphase.prototype.convexCapsule = function( convexBody, convexShape, convexPosition, convexAngle, capsuleBody, capsuleShape, capsulePosition, capsuleAngle, justTest ){ // Check the circles // Add offsets! var circlePos = convexCapsule_tempVec; vec2.set(circlePos, capsuleShape.length/2,0); vec2.rotate(circlePos,circlePos,capsuleAngle); vec2.add(circlePos,circlePos,capsulePosition); var result1 = this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle, convexBody,convexShape,convexPosition,convexAngle, justTest, capsuleShape.radius); vec2.set(circlePos,-capsuleShape.length/2, 0); vec2.rotate(circlePos,circlePos,capsuleAngle); vec2.add(circlePos,circlePos,capsulePosition); var result2 = this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle, convexBody,convexShape,convexPosition,convexAngle, justTest, capsuleShape.radius); if(justTest && (result1 || result2)){ return true; } // Check center rect var r = convexCapsule_tempRect; setConvexToCapsuleShapeMiddle(r,capsuleShape); var result = this.convexConvex(convexBody,convexShape,convexPosition,convexAngle, capsuleBody,r,capsulePosition,capsuleAngle, justTest); return result + result1 + result2; }; /** * Capsule/line narrowphase * @method lineCapsule * @param {Body} lineBody * @param {Line} lineShape * @param {Array} linePosition * @param {Number} lineAngle * @param {Body} capsuleBody * @param {Capsule} capsuleShape * @param {Array} capsulePosition * @param {Number} capsuleAngle * @todo Implement me! */ Narrowphase.prototype[Shape.CAPSULE | Shape.LINE] = Narrowphase.prototype.lineCapsule = function( lineBody, lineShape, linePosition, lineAngle, capsuleBody, capsuleShape, capsulePosition, capsuleAngle, justTest ){ // TODO if(justTest){ return false; } else { return 0; } }; var capsuleCapsule_tempVec1 = vec2.create(); var capsuleCapsule_tempVec2 = vec2.create(); var capsuleCapsule_tempRect1 = new Rectangle(1,1); /** * Capsule/capsule narrowphase * @method capsuleCapsule * @param {Body} bi * @param {Capsule} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Capsule} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CAPSULE | Shape.CAPSULE] = Narrowphase.prototype.capsuleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ var enableFrictionBefore; // Check the circles // Add offsets! var circlePosi = capsuleCapsule_tempVec1, circlePosj = capsuleCapsule_tempVec2; var numContacts = 0; // Need 4 circle checks, between all for(var i=0; i<2; i++){ vec2.set(circlePosi,(i===0?-1:1)*si.length/2,0); vec2.rotate(circlePosi,circlePosi,ai); vec2.add(circlePosi,circlePosi,xi); for(var j=0; j<2; j++){ vec2.set(circlePosj,(j===0?-1:1)*sj.length/2, 0); vec2.rotate(circlePosj,circlePosj,aj); vec2.add(circlePosj,circlePosj,xj); // Temporarily turn off friction if(this.enableFrictionReduction){ enableFrictionBefore = this.enableFriction; this.enableFriction = false; } var result = this.circleCircle(bi,si,circlePosi,ai, bj,sj,circlePosj,aj, justTest, si.radius, sj.radius); if(this.enableFrictionReduction){ this.enableFriction = enableFrictionBefore; } if(justTest && result){ return true; } numContacts += result; } } if(this.enableFrictionReduction){ // Temporarily turn off friction enableFrictionBefore = this.enableFriction; this.enableFriction = false; } // Check circles against the center rectangles var rect = capsuleCapsule_tempRect1; setConvexToCapsuleShapeMiddle(rect,si); var result1 = this.convexCapsule(bi,rect,xi,ai, bj,sj,xj,aj, justTest); if(this.enableFrictionReduction){ this.enableFriction = enableFrictionBefore; } if(justTest && result1){ return true; } numContacts += result1; if(this.enableFrictionReduction){ // Temporarily turn off friction var enableFrictionBefore = this.enableFriction; this.enableFriction = false; } setConvexToCapsuleShapeMiddle(rect,sj); var result2 = this.convexCapsule(bj,rect,xj,aj, bi,si,xi,ai, justTest); if(this.enableFrictionReduction){ this.enableFriction = enableFrictionBefore; } if(justTest && result2){ return true; } numContacts += result2; if(this.enableFrictionReduction){ if(numContacts && this.enableFriction){ this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); } } return numContacts; }; /** * Line/line narrowphase * @method lineLine * @param {Body} bodyA * @param {Line} shapeA * @param {Array} positionA * @param {Number} angleA * @param {Body} bodyB * @param {Line} shapeB * @param {Array} positionB * @param {Number} angleB * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.LINE] = Narrowphase.prototype.lineLine = function( bodyA, shapeA, positionA, angleA, bodyB, shapeB, positionB, angleB, justTest ){ // TODO if(justTest){ return false; } else { return 0; } }; /** * Plane/line Narrowphase * @method planeLine * @param {Body} planeBody * @param {Plane} planeShape * @param {Array} planeOffset * @param {Number} planeAngle * @param {Body} lineBody * @param {Line} lineShape * @param {Array} lineOffset * @param {Number} lineAngle */ Narrowphase.prototype[Shape.PLANE | Shape.LINE] = Narrowphase.prototype.planeLine = function(planeBody, planeShape, planeOffset, planeAngle, lineBody, lineShape, lineOffset, lineAngle, justTest){ var worldVertex0 = tmp1, worldVertex1 = tmp2, worldVertex01 = tmp3, worldVertex11 = tmp4, worldEdge = tmp5, worldEdgeUnit = tmp6, dist = tmp7, worldNormal = tmp8, worldTangent = tmp9, verts = tmpArray, numContacts = 0; // Get start and end points vec2.set(worldVertex0, -lineShape.length/2, 0); vec2.set(worldVertex1, lineShape.length/2, 0); // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired. vec2.rotate(worldVertex01, worldVertex0, lineAngle); vec2.rotate(worldVertex11, worldVertex1, lineAngle); add(worldVertex01, worldVertex01, lineOffset); add(worldVertex11, worldVertex11, lineOffset); vec2.copy(worldVertex0,worldVertex01); vec2.copy(worldVertex1,worldVertex11); // Get vector along the line sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. vec2.rotate90cw(worldTangent, worldEdgeUnit); vec2.rotate(worldNormal, yAxis, planeAngle); // Check line ends verts[0] = worldVertex0; verts[1] = worldVertex1; for(var i=0; i<verts.length; i++){ var v = verts[i]; sub(dist, v, planeOffset); var d = dot(dist,worldNormal); if(d < 0){ if(justTest){ return true; } var c = this.createContactEquation(planeBody,lineBody,planeShape,lineShape); numContacts++; vec2.copy(c.normalA, worldNormal); vec2.normalize(c.normalA,c.normalA); // distance vector along plane normal vec2.scale(dist, worldNormal, d); // Vector from plane center to contact sub(c.contactPointA, v, dist); sub(c.contactPointA, c.contactPointA, planeBody.position); // From line center to contact sub(c.contactPointB, v, lineOffset); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); if(!this.enableFrictionReduction){ if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } } if(justTest){ return false; } if(!this.enableFrictionReduction){ if(numContacts && this.enableFriction){ this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); } } return numContacts; }; Narrowphase.prototype[Shape.PARTICLE | Shape.CAPSULE] = Narrowphase.prototype.particleCapsule = function( particleBody, particleShape, particlePosition, particleAngle, capsuleBody, capsuleShape, capsulePosition, capsuleAngle, justTest ){ return this.circleLine(particleBody,particleShape,particlePosition,particleAngle, capsuleBody,capsuleShape,capsulePosition,capsuleAngle, justTest, capsuleShape.radius, 0); }; /** * Circle/line Narrowphase * @method circleLine * @param {Body} circleBody * @param {Circle} circleShape * @param {Array} circleOffset * @param {Number} circleAngle * @param {Body} lineBody * @param {Line} lineShape * @param {Array} lineOffset * @param {Number} lineAngle * @param {Boolean} justTest If set to true, this function will return the result (intersection or not) without adding equations. * @param {Number} lineRadius Radius to add to the line. Can be used to test Capsules. * @param {Number} circleRadius If set, this value overrides the circle shape radius. */ Narrowphase.prototype[Shape.CIRCLE | Shape.LINE] = Narrowphase.prototype.circleLine = function( circleBody, circleShape, circleOffset, circleAngle, lineBody, lineShape, lineOffset, lineAngle, justTest, lineRadius, circleRadius ){ var lineRadius = lineRadius || 0, circleRadius = typeof(circleRadius)!=="undefined" ? circleRadius : circleShape.radius, orthoDist = tmp1, lineToCircleOrthoUnit = tmp2, projectedPoint = tmp3, centerDist = tmp4, worldTangent = tmp5, worldEdge = tmp6, worldEdgeUnit = tmp7, worldVertex0 = tmp8, worldVertex1 = tmp9, worldVertex01 = tmp10, worldVertex11 = tmp11, dist = tmp12, lineToCircle = tmp13, lineEndToLineRadius = tmp14, verts = tmpArray; // Get start and end points vec2.set(worldVertex0, -lineShape.length/2, 0); vec2.set(worldVertex1, lineShape.length/2, 0); // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired. vec2.rotate(worldVertex01, worldVertex0, lineAngle); vec2.rotate(worldVertex11, worldVertex1, lineAngle); add(worldVertex01, worldVertex01, lineOffset); add(worldVertex11, worldVertex11, lineOffset); vec2.copy(worldVertex0,worldVertex01); vec2.copy(worldVertex1,worldVertex11); // Get vector along the line sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. vec2.rotate90cw(worldTangent, worldEdgeUnit); // Check distance from the plane spanned by the edge vs the circle sub(dist, circleOffset, worldVertex0); var d = dot(dist, worldTangent); // Distance from center of line to circle center sub(centerDist, worldVertex0, lineOffset); sub(lineToCircle, circleOffset, lineOffset); var radiusSum = circleRadius + lineRadius; if(Math.abs(d) < radiusSum){ // Now project the circle onto the edge vec2.scale(orthoDist, worldTangent, d); sub(projectedPoint, circleOffset, orthoDist); // Add the missing line radius vec2.scale(lineToCircleOrthoUnit, worldTangent, dot(worldTangent, lineToCircle)); vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit); vec2.scale(lineToCircleOrthoUnit, lineToCircleOrthoUnit, lineRadius); add(projectedPoint,projectedPoint,lineToCircleOrthoUnit); // Check if the point is within the edge span var pos = dot(worldEdgeUnit, projectedPoint); var pos0 = dot(worldEdgeUnit, worldVertex0); var pos1 = dot(worldEdgeUnit, worldVertex1); if(pos > pos0 && pos < pos1){ // We got contact! if(justTest){ return true; } var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); vec2.scale(c.normalA, orthoDist, -1); vec2.normalize(c.normalA, c.normalA); vec2.scale( c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, projectedPoint, lineOffset); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } // Add corner verts[0] = worldVertex0; verts[1] = worldVertex1; for(var i=0; i<verts.length; i++){ var v = verts[i]; sub(dist, v, circleOffset); if(vec2.squaredLength(dist) < Math.pow(radiusSum, 2)){ if(justTest){ return true; } var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, v, lineOffset); vec2.scale(lineEndToLineRadius, c.normalA, -lineRadius); add(c.contactPointB, c.contactPointB, lineEndToLineRadius); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } return 0; }; /** * Circle/capsule Narrowphase * @method circleCapsule * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.CAPSULE] = Narrowphase.prototype.circleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius); }; /** * Circle/convex Narrowphase. * @method circleConvex * @param {Body} circleBody * @param {Circle} circleShape * @param {Array} circleOffset * @param {Number} circleAngle * @param {Body} convexBody * @param {Convex} convexShape * @param {Array} convexOffset * @param {Number} convexAngle * @param {Boolean} justTest * @param {Number} circleRadius */ Narrowphase.prototype[Shape.CIRCLE | Shape.CONVEX] = Narrowphase.prototype[Shape.CIRCLE | Shape.RECTANGLE] = Narrowphase.prototype.circleConvex = function( circleBody, circleShape, circleOffset, circleAngle, convexBody, convexShape, convexOffset, convexAngle, justTest, circleRadius ){ var circleRadius = typeof(circleRadius)==="number" ? circleRadius : circleShape.radius; var worldVertex0 = tmp1, worldVertex1 = tmp2, worldEdge = tmp3, worldEdgeUnit = tmp4, worldNormal = tmp5, centerDist = tmp6, convexToCircle = tmp7, orthoDist = tmp8, projectedPoint = tmp9, dist = tmp10, worldVertex = tmp11, closestEdge = -1, closestEdgeDistance = null, closestEdgeOrthoDist = tmp12, closestEdgeProjectedPoint = tmp13, candidate = tmp14, candidateDist = tmp15, minCandidate = tmp16, found = false, minCandidateDistance = Number.MAX_VALUE; var numReported = 0; // New algorithm: // 1. Check so center of circle is not inside the polygon. If it is, this wont work... // 2. For each edge // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) // 2. 2. Check if point is inside. var verts = convexShape.vertices; // Check all edges first for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. Points out of the Convex vec2.rotate90cw(worldNormal, worldEdgeUnit); // Get point on circle, closest to the polygon vec2.scale(candidate,worldNormal,-circleShape.radius); add(candidate,candidate,circleOffset); if(pointInConvex(candidate,convexShape,convexOffset,convexAngle)){ vec2.sub(candidateDist,worldVertex0,candidate); var candidateDistance = Math.abs(vec2.dot(candidateDist,worldNormal)); if(candidateDistance < minCandidateDistance){ vec2.copy(minCandidate,candidate); minCandidateDistance = candidateDistance; vec2.scale(closestEdgeProjectedPoint,worldNormal,candidateDistance); vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,candidate); found = true; } } } if(found){ if(justTest){ return true; } var c = this.createContactEquation(circleBody,convexBody,circleShape,convexShape); vec2.sub(c.normalA, minCandidate, circleOffset); vec2.normalize(c.normalA, c.normalA); vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(c) ); } return 1; } // Check all vertices if(circleRadius > 0){ for(var i=0; i<verts.length; i++){ var localVertex = verts[i]; vec2.rotate(worldVertex, localVertex, convexAngle); add(worldVertex, worldVertex, convexOffset); sub(dist, worldVertex, circleOffset); if(vec2.squaredLength(dist) < Math.pow(circleRadius, 2)){ if(justTest){ return true; } var c = this.createContactEquation(circleBody,convexBody,circleShape,convexShape); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, worldVertex, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } } return 0; }; var pic_worldVertex0 = vec2.create(), pic_worldVertex1 = vec2.create(), pic_r0 = vec2.create(), pic_r1 = vec2.create(); /* * Check if a point is in a polygon */ function pointInConvex(worldPoint,convexShape,convexOffset,convexAngle){ var worldVertex0 = pic_worldVertex0, worldVertex1 = pic_worldVertex1, r0 = pic_r0, r1 = pic_r1, point = worldPoint, verts = convexShape.vertices, lastCross = null; for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; // Transform vertices to world // @todo The point should be transformed to local coordinates in the convex, no need to transform each vertex vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); sub(r0, worldVertex0, point); sub(r1, worldVertex1, point); var cross = vec2.crossLength(r0,r1); if(lastCross===null){ lastCross = cross; } // If we got a different sign of the distance vector, the point is out of the polygon if(cross*lastCross <= 0){ return false; } lastCross = cross; } return true; } /** * Particle/convex Narrowphase * @method particleConvex * @param {Body} particleBody * @param {Particle} particleShape * @param {Array} particleOffset * @param {Number} particleAngle * @param {Body} convexBody * @param {Convex} convexShape * @param {Array} convexOffset * @param {Number} convexAngle * @param {Boolean} justTest * @todo use pointInConvex and code more similar to circleConvex * @todo don't transform each vertex, but transform the particle position to convex-local instead */ Narrowphase.prototype[Shape.PARTICLE | Shape.CONVEX] = Narrowphase.prototype[Shape.PARTICLE | Shape.RECTANGLE] = Narrowphase.prototype.particleConvex = function( particleBody, particleShape, particleOffset, particleAngle, convexBody, convexShape, convexOffset, convexAngle, justTest ){ var worldVertex0 = tmp1, worldVertex1 = tmp2, worldEdge = tmp3, worldEdgeUnit = tmp4, worldTangent = tmp5, centerDist = tmp6, convexToparticle = tmp7, orthoDist = tmp8, projectedPoint = tmp9, dist = tmp10, worldVertex = tmp11, closestEdge = -1, closestEdgeDistance = null, closestEdgeOrthoDist = tmp12, closestEdgeProjectedPoint = tmp13, r0 = tmp14, // vector from particle to vertex0 r1 = tmp15, localPoint = tmp16, candidateDist = tmp17, minEdgeNormal = tmp18, minCandidateDistance = Number.MAX_VALUE; var numReported = 0, found = false, verts = convexShape.vertices; // Check if the particle is in the polygon at all if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle)){ return 0; } if(justTest){ return true; } // Check edges first var lastCross = null; for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; // Transform vertices to world vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); // Get world edge sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. Points out of the Convex vec2.rotate90cw(worldTangent, worldEdgeUnit); // Check distance from the infinite line (spanned by the edge) to the particle sub(dist, particleOffset, worldVertex0); var d = dot(dist, worldTangent); sub(centerDist, worldVertex0, convexOffset); sub(convexToparticle, particleOffset, convexOffset); vec2.sub(candidateDist,worldVertex0,particleOffset); var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent)); if(candidateDistance < minCandidateDistance){ minCandidateDistance = candidateDistance; vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance); vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,particleOffset); vec2.copy(minEdgeNormal,worldTangent); found = true; } } if(found){ var c = this.createContactEquation(particleBody,convexBody,particleShape,convexShape); vec2.scale(c.normalA, minEdgeNormal, -1); vec2.normalize(c.normalA, c.normalA); // Particle has no extent to the contact point vec2.set(c.contactPointA, 0, 0); add(c.contactPointA, c.contactPointA, particleOffset); sub(c.contactPointA, c.contactPointA, particleBody.position); // From convex center to point sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(c) ); } return 1; } return 0; }; /** * Circle/circle Narrowphase * @method circleCircle * @param {Body} bodyA * @param {Circle} shapeA * @param {Array} offsetA * @param {Number} angleA * @param {Body} bodyB * @param {Circle} shapeB * @param {Array} offsetB * @param {Number} angleB * @param {Boolean} justTest * @param {Number} [radiusA] Optional radius to use for shapeA * @param {Number} [radiusB] Optional radius to use for shapeB */ Narrowphase.prototype[Shape.CIRCLE] = Narrowphase.prototype.circleCircle = function( bodyA, shapeA, offsetA, angleA, bodyB, shapeB, offsetB, angleB, justTest, radiusA, radiusB ){ var dist = tmp1, radiusA = radiusA || shapeA.radius, radiusB = radiusB || shapeB.radius; sub(dist,offsetA,offsetB); var r = radiusA + radiusB; if(vec2.squaredLength(dist) > Math.pow(r,2)){ return 0; } if(justTest){ return true; } var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); sub(c.normalA, offsetB, offsetA); vec2.normalize(c.normalA,c.normalA); vec2.scale( c.contactPointA, c.normalA, radiusA); vec2.scale( c.contactPointB, c.normalA, -radiusB); add(c.contactPointA, c.contactPointA, offsetA); sub(c.contactPointA, c.contactPointA, bodyA.position); add(c.contactPointB, c.contactPointB, offsetB); sub(c.contactPointB, c.contactPointB, bodyB.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; /** * Plane/Convex Narrowphase * @method planeConvex * @param {Body} planeBody * @param {Plane} planeShape * @param {Array} planeOffset * @param {Number} planeAngle * @param {Body} convexBody * @param {Convex} convexShape * @param {Array} convexOffset * @param {Number} convexAngle * @param {Boolean} justTest */ Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = Narrowphase.prototype[Shape.PLANE | Shape.RECTANGLE] = Narrowphase.prototype.planeConvex = function( planeBody, planeShape, planeOffset, planeAngle, convexBody, convexShape, convexOffset, convexAngle, justTest ){ var worldVertex = tmp1, worldNormal = tmp2, dist = tmp3; var numReported = 0; vec2.rotate(worldNormal, yAxis, planeAngle); for(var i=0; i!==convexShape.vertices.length; i++){ var v = convexShape.vertices[i]; vec2.rotate(worldVertex, v, convexAngle); add(worldVertex, worldVertex, convexOffset); sub(dist, worldVertex, planeOffset); if(dot(dist,worldNormal) <= 0){ if(justTest){ return true; } // Found vertex numReported++; var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); sub(dist, worldVertex, planeOffset); vec2.copy(c.normalA, worldNormal); var d = dot(dist, c.normalA); vec2.scale(dist, c.normalA, d); // rj is from convex center to contact sub(c.contactPointB, worldVertex, convexBody.position); // ri is from plane center to contact sub( c.contactPointA, worldVertex, dist); sub( c.contactPointA, c.contactPointA, planeBody.position); this.contactEquations.push(c); if(!this.enableFrictionReduction){ if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } } if(this.enableFrictionReduction){ if(this.enableFriction && numReported){ this.frictionEquations.push(this.createFrictionFromAverage(numReported)); } } return numReported; }; /** * Narrowphase for particle vs plane * @method particlePlane * @param {Body} particleBody * @param {Particle} particleShape * @param {Array} particleOffset * @param {Number} particleAngle * @param {Body} planeBody * @param {Plane} planeShape * @param {Array} planeOffset * @param {Number} planeAngle * @param {Boolean} justTest */ Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = Narrowphase.prototype.particlePlane = function( particleBody, particleShape, particleOffset, particleAngle, planeBody, planeShape, planeOffset, planeAngle, justTest ){ var dist = tmp1, worldNormal = tmp2; planeAngle = planeAngle || 0; sub(dist, particleOffset, planeOffset); vec2.rotate(worldNormal, yAxis, planeAngle); var d = dot(dist, worldNormal); if(d > 0){ return 0; } if(justTest){ return true; } var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); vec2.copy(c.normalA, worldNormal); vec2.scale( dist, c.normalA, d ); // dist is now the distance vector in the normal direction // ri is the particle position projected down onto the plane, from the plane center sub( c.contactPointA, particleOffset, dist); sub( c.contactPointA, c.contactPointA, planeBody.position); // rj is from the body center to the particle center sub( c.contactPointB, particleOffset, particleBody.position ); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; /** * Circle/Particle Narrowphase * @method circleParticle * @param {Body} circleBody * @param {Circle} circleShape * @param {Array} circleOffset * @param {Number} circleAngle * @param {Body} particleBody * @param {Particle} particleShape * @param {Array} particleOffset * @param {Number} particleAngle * @param {Boolean} justTest */ Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = Narrowphase.prototype.circleParticle = function( circleBody, circleShape, circleOffset, circleAngle, particleBody, particleShape, particleOffset, particleAngle, justTest ){ var dist = tmp1; sub(dist, particleOffset, circleOffset); if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ return 0; } if(justTest){ return true; } var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleShape.radius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); // Vector from particle center to contact point is zero sub(c.contactPointB, particleOffset, particleBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; var planeCapsule_tmpCircle = new Circle(1), planeCapsule_tmp1 = vec2.create(), planeCapsule_tmp2 = vec2.create(), planeCapsule_tmp3 = vec2.create(); /** * @method planeCapsule * @param {Body} planeBody * @param {Circle} planeShape * @param {Array} planeOffset * @param {Number} planeAngle * @param {Body} capsuleBody * @param {Particle} capsuleShape * @param {Array} capsuleOffset * @param {Number} capsuleAngle * @param {Boolean} justTest */ Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = Narrowphase.prototype.planeCapsule = function( planeBody, planeShape, planeOffset, planeAngle, capsuleBody, capsuleShape, capsuleOffset, capsuleAngle, justTest ){ var end1 = planeCapsule_tmp1, end2 = planeCapsule_tmp2, circle = planeCapsule_tmpCircle, dst = planeCapsule_tmp3; // Compute world end positions vec2.set(end1, -capsuleShape.length/2, 0); vec2.rotate(end1,end1,capsuleAngle); add(end1,end1,capsuleOffset); vec2.set(end2, capsuleShape.length/2, 0); vec2.rotate(end2,end2,capsuleAngle); add(end2,end2,capsuleOffset); circle.radius = capsuleShape.radius; var enableFrictionBefore; // Temporarily turn off friction if(this.enableFrictionReduction){ enableFrictionBefore = this.enableFriction; this.enableFriction = false; } // Do Narrowphase as two circles var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); // Restore friction if(this.enableFrictionReduction){ this.enableFriction = enableFrictionBefore; } if(justTest){ return numContacts1 || numContacts2; } else { var numTotal = numContacts1 + numContacts2; if(this.enableFrictionReduction){ if(numTotal){ this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); } } return numTotal; } }; /** * Creates ContactEquations and FrictionEquations for a collision. * @method circlePlane * @param {Body} bi The first body that should be connected to the equations. * @param {Circle} si The circle shape participating in the collision. * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. * @param {Body} bj The second body that should be connected to the equations. * @param {Plane} sj The Plane shape that is participating * @param {Array} xj Extra offset for the plane shape. * @param {Number} aj Extra angle to apply to the plane */ Narrowphase.prototype[Shape.CIRCLE | Shape.PLANE] = Narrowphase.prototype.circlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var circleBody = bi, circleShape = si, circleOffset = xi, // Offset from body center, rotated! planeBody = bj, shapeB = sj, planeOffset = xj, planeAngle = aj; planeAngle = planeAngle || 0; // Vector from plane to circle var planeToCircle = tmp1, worldNormal = tmp2, temp = tmp3; sub(planeToCircle, circleOffset, planeOffset); // World plane normal vec2.rotate(worldNormal, yAxis, planeAngle); // Normal direction distance var d = dot(worldNormal, planeToCircle); if(d > circleShape.radius){ return 0; // No overlap. Abort. } if(justTest){ return true; } // Create contact var contact = this.createContactEquation(planeBody,circleBody,sj,si); // ni is the plane world normal vec2.copy(contact.normalA, worldNormal); // rj is the vector from circle center to the contact point vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); add(contact.contactPointB, contact.contactPointB, circleOffset); sub(contact.contactPointB, contact.contactPointB, circleBody.position); // ri is the distance from plane center to contact. vec2.scale(temp, contact.normalA, d); sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector add(contact.contactPointA, contact.contactPointA, planeOffset); sub(contact.contactPointA, contact.contactPointA, planeBody.position); this.contactEquations.push(contact); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(contact) ); } return 1; }; /** * Convex/convex Narrowphase.See <a href="http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/">this article</a> for more info. * @method convexConvex * @param {Body} bi * @param {Convex} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CONVEX] = Narrowphase.prototype[Shape.CONVEX | Shape.RECTANGLE] = Narrowphase.prototype[Shape.RECTANGLE] = Narrowphase.prototype.convexConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, precision ){ var sepAxis = tmp1, worldPoint = tmp2, worldPoint0 = tmp3, worldPoint1 = tmp4, worldEdge = tmp5, projected = tmp6, penetrationVec = tmp7, dist = tmp8, worldNormal = tmp9, numContacts = 0, precision = typeof(precision) === 'number' ? precision : 0; var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); if(!found){ return 0; } // Make sure the separating axis is directed from shape i to shape j sub(dist,xj,xi); if(dot(sepAxis,dist) > 0){ vec2.scale(sepAxis,sepAxis,-1); } // Find edges with normals closest to the separating axis var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); if(closestEdge1 === -1 || closestEdge2 === -1){ return 0; } // Loop over the shapes for(var k=0; k<2; k++){ var closestEdgeA = closestEdge1, closestEdgeB = closestEdge2, shapeA = si, shapeB = sj, offsetA = xi, offsetB = xj, angleA = ai, angleB = aj, bodyA = bi, bodyB = bj; if(k === 0){ // Swap! var tmp; tmp = closestEdgeA; closestEdgeA = closestEdgeB; closestEdgeB = tmp; tmp = shapeA; shapeA = shapeB; shapeB = tmp; tmp = offsetA; offsetA = offsetB; offsetB = tmp; tmp = angleA; angleA = angleB; angleB = tmp; tmp = bodyA; bodyA = bodyB; bodyB = tmp; } // Loop over 2 points in convex B for(var j=closestEdgeB; j<closestEdgeB+2; j++){ // Get world point var v = shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length]; vec2.rotate(worldPoint, v, angleB); add(worldPoint, worldPoint, offsetB); var insideNumEdges = 0; // Loop over the 3 closest edges in convex A for(var i=closestEdgeA-1; i<closestEdgeA+2; i++){ var v0 = shapeA.vertices[(i +shapeA.vertices.length)%shapeA.vertices.length], v1 = shapeA.vertices[(i+1+shapeA.vertices.length)%shapeA.vertices.length]; // Construct the edge vec2.rotate(worldPoint0, v0, angleA); vec2.rotate(worldPoint1, v1, angleA); add(worldPoint0, worldPoint0, offsetA); add(worldPoint1, worldPoint1, offsetA); sub(worldEdge, worldPoint1, worldPoint0); vec2.rotate90cw(worldNormal, worldEdge); // Normal points out of convex 1 vec2.normalize(worldNormal,worldNormal); sub(dist, worldPoint, worldPoint0); var d = dot(worldNormal,dist); if((i === closestEdgeA && d <= precision) || (i !== closestEdgeA && d <= 0)){ insideNumEdges++; } } if(insideNumEdges >= 3){ if(justTest){ return true; } // worldPoint was on the "inside" side of each of the 3 checked edges. // Project it to the center edge and use the projection direction as normal // Create contact var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); numContacts++; // Get center edge from body A var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; // Construct the edge vec2.rotate(worldPoint0, v0, angleA); vec2.rotate(worldPoint1, v1, angleA); add(worldPoint0, worldPoint0, offsetA); add(worldPoint1, worldPoint1, offsetA); sub(worldEdge, worldPoint1, worldPoint0); vec2.rotate90cw(c.normalA, worldEdge); // Normal points out of convex A vec2.normalize(c.normalA,c.normalA); sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point var d = dot(c.normalA,dist); // Penetration vec2.scale(penetrationVec, c.normalA, d); // Vector penetration sub(c.contactPointA, worldPoint, offsetA); sub(c.contactPointA, c.contactPointA, penetrationVec); add(c.contactPointA, c.contactPointA, offsetA); sub(c.contactPointA, c.contactPointA, bodyA.position); sub(c.contactPointB, worldPoint, offsetB); add(c.contactPointB, c.contactPointB, offsetB); sub(c.contactPointB, c.contactPointB, bodyB.position); this.contactEquations.push(c); // Todo reduce to 1 friction equation if we have 2 contact points if(!this.enableFrictionReduction){ if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } } } if(this.enableFrictionReduction){ if(this.enableFriction && numContacts){ this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); } } return numContacts; }; // .projectConvex is called by other functions, need local tmp vectors var pcoa_tmp1 = vec2.fromValues(0,0); /** * Project a Convex onto a world-oriented axis * @method projectConvexOntoAxis * @static * @param {Convex} convexShape * @param {Array} convexOffset * @param {Number} convexAngle * @param {Array} worldAxis * @param {Array} result */ Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ var max=null, min=null, v, value, localAxis = pcoa_tmp1; // Convert the axis to local coords of the body vec2.rotate(localAxis, worldAxis, -convexAngle); // Get projected position of all vertices for(var i=0; i<convexShape.vertices.length; i++){ v = convexShape.vertices[i]; value = dot(v,localAxis); if(max === null || value > max){ max = value; } if(min === null || value < min){ min = value; } } if(min > max){ var t = min; min = max; max = t; } // Project the position of the body onto the axis - need to add this to the result var offset = dot(convexOffset, worldAxis); vec2.set( result, min + offset, max + offset); }; // .findSeparatingAxis is called by other functions, need local tmp vectors var fsa_tmp1 = vec2.fromValues(0,0) , fsa_tmp2 = vec2.fromValues(0,0) , fsa_tmp3 = vec2.fromValues(0,0) , fsa_tmp4 = vec2.fromValues(0,0) , fsa_tmp5 = vec2.fromValues(0,0) , fsa_tmp6 = vec2.fromValues(0,0); /** * Find a separating axis between the shapes, that maximizes the separating distance between them. * @method findSeparatingAxis * @static * @param {Convex} c1 * @param {Array} offset1 * @param {Number} angle1 * @param {Convex} c2 * @param {Array} offset2 * @param {Number} angle2 * @param {Array} sepAxis The resulting axis * @return {Boolean} Whether the axis could be found. */ Narrowphase.findSeparatingAxis = function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){ var maxDist = null, overlap = false, found = false, edge = fsa_tmp1, worldPoint0 = fsa_tmp2, worldPoint1 = fsa_tmp3, normal = fsa_tmp4, span1 = fsa_tmp5, span2 = fsa_tmp6; if(c1 instanceof Rectangle && c2 instanceof Rectangle){ for(var j=0; j!==2; j++){ var c = c1, angle = angle1; if(j===1){ c = c2; angle = angle2; } for(var i=0; i!==2; i++){ // Get the world edge if(i === 0){ vec2.set(normal, 0, 1); } else if(i === 1) { vec2.set(normal, 1, 0); } if(angle !== 0){ vec2.rotate(normal, normal, angle); } // Project hulls onto that normal Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); // Order by span position var a=span1, b=span2, swapped = false; if(span1[0] > span2[0]){ b=span1; a=span2; swapped = true; } // Get separating distance var dist = b[0] - a[1]; overlap = (dist <= 0); if(maxDist===null || dist > maxDist){ vec2.copy(sepAxis, normal); maxDist = dist; found = overlap; } } } } else { for(var j=0; j!==2; j++){ var c = c1, angle = angle1; if(j===1){ c = c2; angle = angle2; } for(var i=0; i!==c.vertices.length; i++){ // Get the world edge vec2.rotate(worldPoint0, c.vertices[i], angle); vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); sub(edge, worldPoint1, worldPoint0); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, edge); vec2.normalize(normal,normal); // Project hulls onto that normal Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); // Order by span position var a=span1, b=span2, swapped = false; if(span1[0] > span2[0]){ b=span1; a=span2; swapped = true; } // Get separating distance var dist = b[0] - a[1]; overlap = (dist <= 0); if(maxDist===null || dist > maxDist){ vec2.copy(sepAxis, normal); maxDist = dist; found = overlap; } } } } /* // Needs to be tested some more for(var j=0; j!==2; j++){ var c = c1, angle = angle1; if(j===1){ c = c2; angle = angle2; } for(var i=0; i!==c.axes.length; i++){ var normal = c.axes[i]; // Project hulls onto that normal Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); // Order by span position var a=span1, b=span2, swapped = false; if(span1[0] > span2[0]){ b=span1; a=span2; swapped = true; } // Get separating distance var dist = b[0] - a[1]; overlap = (dist <= Narrowphase.convexPrecision); if(maxDist===null || dist > maxDist){ vec2.copy(sepAxis, normal); maxDist = dist; found = overlap; } } } */ return found; }; // .getClosestEdge is called by other functions, need local tmp vectors var gce_tmp1 = vec2.fromValues(0,0) , gce_tmp2 = vec2.fromValues(0,0) , gce_tmp3 = vec2.fromValues(0,0); /** * Get the edge that has a normal closest to an axis. * @method getClosestEdge * @static * @param {Convex} c * @param {Number} angle * @param {Array} axis * @param {Boolean} flip * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. */ Narrowphase.getClosestEdge = function(c,angle,axis,flip){ var localAxis = gce_tmp1, edge = gce_tmp2, normal = gce_tmp3; // Convert the axis to local coords of the body vec2.rotate(localAxis, axis, -angle); if(flip){ vec2.scale(localAxis,localAxis,-1); } var closestEdge = -1, N = c.vertices.length, maxDot = -1; for(var i=0; i!==N; i++){ // Get the edge sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, edge); vec2.normalize(normal,normal); var d = dot(normal,localAxis); if(closestEdge === -1 || d > maxDot){ closestEdge = i % N; maxDot = d; } } return closestEdge; }; var circleHeightfield_candidate = vec2.create(), circleHeightfield_dist = vec2.create(), circleHeightfield_v0 = vec2.create(), circleHeightfield_v1 = vec2.create(), circleHeightfield_minCandidate = vec2.create(), circleHeightfield_worldNormal = vec2.create(), circleHeightfield_minCandidateNormal = vec2.create(); /** * @method circleHeightfield * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Body} bj * @param {Heightfield} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ var data = hfShape.data, radius = radius || circleShape.radius, w = hfShape.elementWidth, dist = circleHeightfield_dist, candidate = circleHeightfield_candidate, minCandidate = circleHeightfield_minCandidate, minCandidateNormal = circleHeightfield_minCandidateNormal, worldNormal = circleHeightfield_worldNormal, v0 = circleHeightfield_v0, v1 = circleHeightfield_v1; // Get the index of the points to test against var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); /*if(idxB < 0 || idxA >= data.length) return justTest ? false : 0;*/ if(idxA < 0){ idxA = 0; } if(idxB >= data.length){ idxB = data.length-1; } // Get max and min var max = data[idxA], min = data[idxB]; for(var i=idxA; i<idxB; i++){ if(data[i] < min){ min = data[i]; } if(data[i] > max){ max = data[i]; } } if(circlePos[1]-radius > max){ return justTest ? false : 0; } /* if(circlePos[1]+radius < min){ // Below the minimum point... We can just guess. // TODO } */ // 1. Check so center of circle is not inside the field. If it is, this wont work... // 2. For each edge // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) // 2. 2. Check if point is inside. var found = false; // Check all edges first for(var i=idxA; i<idxB; i++){ // Get points vec2.set(v0, i*w, data[i] ); vec2.set(v1, (i+1)*w, data[i+1]); vec2.add(v0,v0,hfPos); vec2.add(v1,v1,hfPos); // Get normal vec2.sub(worldNormal, v1, v0); vec2.rotate(worldNormal, worldNormal, Math.PI/2); vec2.normalize(worldNormal,worldNormal); // Get point on circle, closest to the edge vec2.scale(candidate,worldNormal,-radius); vec2.add(candidate,candidate,circlePos); // Distance from v0 to the candidate point vec2.sub(dist,candidate,v0); // Check if it is in the element "stick" var d = vec2.dot(dist,worldNormal); if(candidate[0] >= v0[0] && candidate[0] < v1[0] && d <= 0){ if(justTest){ return true; } found = true; // Store the candidate point, projected to the edge vec2.scale(dist,worldNormal,-d); vec2.add(minCandidate,candidate,dist); vec2.copy(minCandidateNormal,worldNormal); var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); // Normal is out of the heightfield vec2.copy(c.normalA, minCandidateNormal); // Vector from circle to heightfield vec2.scale(c.contactPointB, c.normalA, -radius); add(c.contactPointB, c.contactPointB, circlePos); sub(c.contactPointB, c.contactPointB, circleBody.position); vec2.copy(c.contactPointA, minCandidate); vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(c) ); } } } // Check all vertices found = false; if(radius > 0){ for(var i=idxA; i<=idxB; i++){ // Get point vec2.set(v0, i*w, data[i]); vec2.add(v0,v0,hfPos); vec2.sub(dist, circlePos, v0); if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ if(justTest){ return true; } found = true; var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); // Construct normal - out of heightfield vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); vec2.scale(c.contactPointB, c.normalA, -radius); add(c.contactPointB, c.contactPointB, circlePos); sub(c.contactPointB, c.contactPointB, circleBody.position); sub(c.contactPointA, v0, hfPos); add(c.contactPointA, c.contactPointA, hfPos); sub(c.contactPointA, c.contactPointA, hfBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } } if(found){ return 1; } return 0; }; var convexHeightfield_v0 = vec2.create(), convexHeightfield_v1 = vec2.create(), convexHeightfield_tilePos = vec2.create(), convexHeightfield_tempConvexShape = new Convex([vec2.create(),vec2.create(),vec2.create(),vec2.create()]); /** * @method circleHeightfield * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Body} bj * @param {Heightfield} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.RECTANGLE | Shape.HEIGHTFIELD] = Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, hfBody,hfShape,hfPos,hfAngle, justTest ){ var data = hfShape.data, w = hfShape.elementWidth, v0 = convexHeightfield_v0, v1 = convexHeightfield_v1, tilePos = convexHeightfield_tilePos, tileConvex = convexHeightfield_tempConvexShape; // Get the index of the points to test against var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); if(idxA < 0){ idxA = 0; } if(idxB >= data.length){ idxB = data.length-1; } // Get max and min var max = data[idxA], min = data[idxB]; for(var i=idxA; i<idxB; i++){ if(data[i] < min){ min = data[i]; } if(data[i] > max){ max = data[i]; } } if(convexBody.aabb.lowerBound[1] > max){ return justTest ? false : 0; } var found = false; var numContacts = 0; // Loop over all edges // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) for(var i=idxA; i<idxB; i++){ // Get points vec2.set(v0, i*w, data[i] ); vec2.set(v1, (i+1)*w, data[i+1]); vec2.add(v0,v0,hfPos); vec2.add(v1,v1,hfPos); // Construct a convex var tileHeight = 100; // todo vec2.set(tilePos, (v1[0] + v0[0])*0.5, (v1[1] + v0[1] - tileHeight)*0.5); vec2.sub(tileConvex.vertices[0], v1, tilePos); vec2.sub(tileConvex.vertices[1], v0, tilePos); vec2.copy(tileConvex.vertices[2], tileConvex.vertices[1]); vec2.copy(tileConvex.vertices[3], tileConvex.vertices[0]); tileConvex.vertices[2][1] -= tileHeight; tileConvex.vertices[3][1] -= tileHeight; // Do convex collision numContacts += this.convexConvex( convexBody, convexShape, convexPos, convexAngle, hfBody, tileConvex, tilePos, 0, justTest); } return numContacts; }; },{"../equations/ContactEquation":22,"../equations/Equation":23,"../equations/FrictionEquation":24,"../math/vec2":31,"../objects/Body":32,"../shapes/Circle":38,"../shapes/Convex":39,"../shapes/Rectangle":44,"../shapes/Shape":45,"../utils/TupleDictionary":49,"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],14:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/collision\\SAPBroadphase.js",__dirname="/collision";var Utils = require('../utils/Utils') , Broadphase = require('../collision/Broadphase'); module.exports = SAPBroadphase; /** * Sweep and prune broadphase along one axis. * * @class SAPBroadphase * @constructor * @extends Broadphase */ function SAPBroadphase(){ Broadphase.call(this,Broadphase.SAP); /** * List of bodies currently in the broadphase. * @property axisList * @type {Array} */ this.axisList = []; /** * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. * @property axisIndex * @type {Number} */ this.axisIndex = 0; var that = this; this._addBodyHandler = function(e){ that.axisList.push(e.body); }; this._removeBodyHandler = function(e){ // Remove from list var idx = that.axisList.indexOf(e.body); if(idx !== -1){ that.axisList.splice(idx,1); } }; } SAPBroadphase.prototype = new Broadphase(); /** * Change the world * @method setWorld * @param {World} world */ SAPBroadphase.prototype.setWorld = function(world){ // Clear the old axis array this.axisList.length = 0; // Add all bodies from the new world Utils.appendArray(this.axisList, world.bodies); // Remove old handlers, if any world .off("addBody",this._addBodyHandler) .off("removeBody",this._removeBodyHandler); // Add handlers to update the list of bodies. world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); this.world = world; }; /** * Sorts bodies along an axis. * @method sortAxisList * @param {Array} a * @param {number} axisIndex * @return {Array} */ SAPBroadphase.sortAxisList = function(a, axisIndex){ axisIndex = axisIndex|0; for(var i=1,l=a.length; i<l; i++) { var v = a[i]; for(var j=i - 1;j>=0;j--) { if(a[j].aabb.lowerBound[axisIndex] <= v.aabb.lowerBound[axisIndex]){ break; } a[j+1] = a[j]; } a[j+1] = v; } return a; }; /** * Get the colliding pairs * @method getCollisionPairs * @param {World} world * @return {Array} */ SAPBroadphase.prototype.getCollisionPairs = function(world){ var bodies = this.axisList, result = this.result, axisIndex = this.axisIndex; result.length = 0; // Update all AABBs if needed var l = bodies.length; while(l--){ var b = bodies[l]; if(b.aabbNeedsUpdate){ b.updateAABB(); } } // Sort the lists SAPBroadphase.sortAxisList(bodies, axisIndex); // Look through the X list for(var i=0, N=bodies.length|0; i!==N; i++){ var bi = bodies[i]; for(var j=i+1; j<N; j++){ var bj = bodies[j]; // Bounds overlap? var overlaps = (bj.aabb.lowerBound[axisIndex] <= bi.aabb.upperBound[axisIndex]); if(!overlaps){ break; } if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } return result; }; },{"../collision/Broadphase":10,"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],15:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/constraints\\Constraint.js",__dirname="/constraints";module.exports = Constraint; var Utils = require('../utils/Utils'); /** * Base constraint class. * * @class Constraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Number} type * @param {Object} [options] * @param {Object} [options.collideConnected=true] */ function Constraint(bodyA, bodyB, type, options){ /** * The type of constraint. May be one of Constraint.DISTANCE, Constraint.GEAR, Constraint.LOCK, Constraint.PRISMATIC or Constraint.REVOLUTE. * @property {number} type */ this.type = type; options = Utils.defaults(options,{ collideConnected : true, wakeUpBodies : true, }); /** * Equations to be solved in this constraint * * @property equations * @type {Array} */ this.equations = []; /** * First body participating in the constraint. * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second body participating in the constraint. * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * Set to true if you want the connected bodies to collide. * @property collideConnected * @type {Boolean} * @default true */ this.collideConnected = options.collideConnected; // Wake up bodies when connected if(options.wakeUpBodies){ if(bodyA){ bodyA.wakeUp(); } if(bodyB){ bodyB.wakeUp(); } } } /** * Updates the internal constraint parameters before solve. * @method update */ Constraint.prototype.update = function(){ throw new Error("method update() not implmemented in this Constraint subclass!"); }; /** * @static * @property {number} DISTANCE */ Constraint.DISTANCE = 1; /** * @static * @property {number} GEAR */ Constraint.GEAR = 2; /** * @static * @property {number} LOCK */ Constraint.LOCK = 3; /** * @static * @property {number} PRISMATIC */ Constraint.PRISMATIC = 4; /** * @static * @property {number} REVOLUTE */ Constraint.REVOLUTE = 5; /** * Set stiffness for this constraint. * @method setStiffness * @param {Number} stiffness */ Constraint.prototype.setStiffness = function(stiffness){ var eqs = this.equations; for(var i=0; i !== eqs.length; i++){ var eq = eqs[i]; eq.stiffness = stiffness; eq.needsUpdate = true; } }; /** * Set relaxation for this constraint. * @method setRelaxation * @param {Number} relaxation */ Constraint.prototype.setRelaxation = function(relaxation){ var eqs = this.equations; for(var i=0; i !== eqs.length; i++){ var eq = eqs[i]; eq.relaxation = relaxation; eq.needsUpdate = true; } }; },{"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],16:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/constraints\\DistanceConstraint.js",__dirname="/constraints";var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = DistanceConstraint; /** * Constraint that tries to keep the distance between two bodies constant. * * @class DistanceConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {object} [options] * @param {number} [options.distance] The distance to keep between the anchor points. Defaults to the current distance between the bodies. * @param {Array} [options.localAnchorA] The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. * @param {Array} [options.localAnchorB] The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. * @param {object} [options.maxForce=Number.MAX_VALUE] Maximum force to apply. * @extends Constraint * * @example * // If distance is not given as an option, then the current distance between the bodies is used. * // In this example, the bodies will be constrained to have a distance of 2 between their centers. * var bodyA = new Body({ mass: 1, position: [-1, 0] }); * var bodyB = new Body({ mass: 1, position: [1, 0] }); * var constraint = new DistanceConstraint(bodyA, bodyB); * * @example * var constraint = new DistanceConstraint(bodyA, bodyB, { * distance: 1, // Distance to keep between the points * localAnchorA: [1, 0], // Point on bodyA * localAnchorB: [-1, 0] // Point on bodyB * }); */ function DistanceConstraint(bodyA,bodyB,options){ options = Utils.defaults(options,{ localAnchorA:[0,0], localAnchorB:[0,0] }); Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE,options); /** * Local anchor in body A. * @property localAnchorA * @type {Array} */ this.localAnchorA = vec2.fromValues(options.localAnchorA[0], options.localAnchorA[1]); /** * Local anchor in body B. * @property localAnchorB * @type {Array} */ this.localAnchorB = vec2.fromValues(options.localAnchorB[0], options.localAnchorB[1]); var localAnchorA = this.localAnchorA; var localAnchorB = this.localAnchorB; /** * The distance to keep. * @property distance * @type {Number} */ this.distance = 0; if(typeof(options.distance) === 'number'){ this.distance = options.distance; } else { // Use the current world distance between the world anchor points. var worldAnchorA = vec2.create(), worldAnchorB = vec2.create(), r = vec2.create(); // Transform local anchors to world vec2.rotate(worldAnchorA, localAnchorA, bodyA.angle); vec2.rotate(worldAnchorB, localAnchorB, bodyB.angle); vec2.add(r, bodyB.position, worldAnchorB); vec2.sub(r, r, worldAnchorA); vec2.sub(r, r, bodyA.position); this.distance = vec2.length(r); } var maxForce; if(typeof(options.maxForce)==="undefined" ){ maxForce = Number.MAX_VALUE; } else { maxForce = options.maxForce; } var normal = new Equation(bodyA,bodyB,-maxForce,maxForce); // Just in the normal direction this.equations = [ normal ]; /** * Max force to apply. * @property {number} maxForce */ this.maxForce = maxForce; // g = (xi - xj).dot(n) // dg/dt = (vi - vj).dot(n) = G*W = [n 0 -n 0] * [vi wi vj wj]' // ...and if we were to include offset points (TODO for now): // g = // (xj + rj - xi - ri).dot(n) - distance // // dg/dt = // (vj + wj x rj - vi - wi x ri).dot(n) = // { term 2 is near zero } = // [-n -ri x n n rj x n] * [vi wi vj wj]' = // G * W // // => G = [-n -rixn n rjxn] var r = vec2.create(); var ri = vec2.create(); // worldAnchorA var rj = vec2.create(); // worldAnchorB var that = this; normal.computeGq = function(){ var bodyA = this.bodyA, bodyB = this.bodyB, xi = bodyA.position, xj = bodyB.position; // Transform local anchors to world vec2.rotate(ri, localAnchorA, bodyA.angle); vec2.rotate(rj, localAnchorB, bodyB.angle); vec2.add(r, xj, rj); vec2.sub(r, r, ri); vec2.sub(r, r, xi); //vec2.sub(r, bodyB.position, bodyA.position); return vec2.length(r) - that.distance; }; // Make the contact constraint bilateral this.setMaxForce(maxForce); /** * If the upper limit is enabled or not. * @property {Boolean} upperLimitEnabled */ this.upperLimitEnabled = false; /** * The upper constraint limit. * @property {number} upperLimit */ this.upperLimit = 1; /** * If the lower limit is enabled or not. * @property {Boolean} lowerLimitEnabled */ this.lowerLimitEnabled = false; /** * The lower constraint limit. * @property {number} lowerLimit */ this.lowerLimit = 0; /** * Current constraint position. This is equal to the current distance between the world anchor points. * @property {number} position */ this.position = 0; } DistanceConstraint.prototype = new Constraint(); /** * Update the constraint equations. Should be done if any of the bodies changed position, before solving. * @method update */ var n = vec2.create(); var ri = vec2.create(); // worldAnchorA var rj = vec2.create(); // worldAnchorB DistanceConstraint.prototype.update = function(){ var normal = this.equations[0], bodyA = this.bodyA, bodyB = this.bodyB, distance = this.distance, xi = bodyA.position, xj = bodyB.position, normalEquation = this.equations[0], G = normal.G; // Transform local anchors to world vec2.rotate(ri, this.localAnchorA, bodyA.angle); vec2.rotate(rj, this.localAnchorB, bodyB.angle); // Get world anchor points and normal vec2.add(n, xj, rj); vec2.sub(n, n, ri); vec2.sub(n, n, xi); this.position = vec2.length(n); var violating = false; if(this.upperLimitEnabled){ if(this.position > this.upperLimit){ normalEquation.maxForce = 0; normalEquation.minForce = -this.maxForce; this.distance = this.upperLimit; violating = true; } } if(this.lowerLimitEnabled){ if(this.position < this.lowerLimit){ normalEquation.maxForce = this.maxForce; normalEquation.minForce = 0; this.distance = this.lowerLimit; violating = true; } } if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ // No constraint needed. normalEquation.enabled = false; return; } normalEquation.enabled = true; vec2.normalize(n,n); // Caluclate cross products var rixn = vec2.crossLength(ri, n), rjxn = vec2.crossLength(rj, n); // G = [-n -rixn n rjxn] G[0] = -n[0]; G[1] = -n[1]; G[2] = -rixn; G[3] = n[0]; G[4] = n[1]; G[5] = rjxn; }; /** * Set the max force to be used * @method setMaxForce * @param {Number} f */ DistanceConstraint.prototype.setMaxForce = function(f){ var normal = this.equations[0]; normal.minForce = -f; normal.maxForce = f; }; /** * Get the max force * @method getMaxForce * @return {Number} */ DistanceConstraint.prototype.getMaxForce = function(f){ var normal = this.equations[0]; return normal.maxForce; }; },{"../equations/Equation":23,"../math/vec2":31,"../utils/Utils":50,"./Constraint":15,"__browserify_Buffer":1,"__browserify_process":2}],17:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/constraints\\GearConstraint.js",__dirname="/constraints";var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , AngleLockEquation = require('../equations/AngleLockEquation') , vec2 = require('../math/vec2'); module.exports = GearConstraint; /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * @class GearConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). * @param {Number} [options.ratio=1] Gear ratio. * @param {Number} [options.maxTorque] Maximum torque to apply. * @extends Constraint * @todo Ability to specify world points */ function GearConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); /** * The gear ratio. * @property ratio * @type {Number} */ this.ratio = typeof(options.ratio) === "number" ? options.ratio : 1; /** * The relative angle * @property angle * @type {Number} */ this.angle = typeof(options.angle) === "number" ? options.angle : bodyB.angle - this.ratio * bodyA.angle; // Send same parameters to the equation options.angle = this.angle; options.ratio = this.ratio; this.equations = [ new AngleLockEquation(bodyA,bodyB,options), ]; // Set max torque if(typeof(options.maxTorque) === "number"){ this.setMaxTorque(options.maxTorque); } } GearConstraint.prototype = new Constraint(); GearConstraint.prototype.update = function(){ var eq = this.equations[0]; if(eq.ratio !== this.ratio){ eq.setRatio(this.ratio); } eq.angle = this.angle; }; /** * Set the max torque for the constraint. * @method setMaxTorque * @param {Number} torque */ GearConstraint.prototype.setMaxTorque = function(torque){ this.equations[0].setMaxTorque(torque); }; /** * Get the max torque for the constraint. * @method getMaxTorque * @return {Number} */ GearConstraint.prototype.getMaxTorque = function(torque){ return this.equations[0].maxForce; }; },{"../equations/AngleLockEquation":21,"../equations/Equation":23,"../math/vec2":31,"./Constraint":15,"__browserify_Buffer":1,"__browserify_process":2}],18:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/constraints\\LockConstraint.js",__dirname="/constraints";var Constraint = require('./Constraint') , vec2 = require('../math/vec2') , Equation = require('../equations/Equation'); module.exports = LockConstraint; /** * Locks the relative position between two bodies. * * @class LockConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. * @param {number} [options.maxForce] * @extends Constraint */ function LockConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); var localAngleB = options.localAngleB || 0; // Use 3 equations: // gx = (xj - xi - l) * xhat = 0 // gy = (xj - xi - l) * yhat = 0 // gr = (xi - xj + r) * that = 0 // // ...where: // l is the localOffsetB vector rotated to world in bodyA frame // r is the same vector but reversed and rotated from bodyB frame // xhat, yhat are world axis vectors // that is the tangent of r // // For the first two constraints, we get // G*W = (vj - vi - ldot ) * xhat // = (vj - vi - wi x l) * xhat // // Since (wi x l) * xhat = (l x xhat) * wi, we get // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] // // The last constraint gives // GW = (vi - vj + wj x r) * that // = [ that 0 -that (r x t) ] var x = new Equation(bodyA,bodyB,-maxForce,maxForce), y = new Equation(bodyA,bodyB,-maxForce,maxForce), rot = new Equation(bodyA,bodyB,-maxForce,maxForce); var l = vec2.create(), g = vec2.create(), that = this; x.computeGq = function(){ vec2.rotate(l, that.localOffsetB, bodyA.angle); vec2.sub(g, bodyB.position, bodyA.position); vec2.sub(g, g, l); return g[0]; }; y.computeGq = function(){ vec2.rotate(l, that.localOffsetB, bodyA.angle); vec2.sub(g, bodyB.position, bodyA.position); vec2.sub(g, g, l); return g[1]; }; var r = vec2.create(), t = vec2.create(); rot.computeGq = function(){ vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); vec2.scale(r,r,-1); vec2.sub(g,bodyA.position,bodyB.position); vec2.add(g,g,r); vec2.rotate(t,r,-Math.PI/2); vec2.normalize(t,t); return vec2.dot(g,t); }; /** * The offset of bodyB in bodyA's frame. * @property {Array} localOffsetB */ this.localOffsetB = vec2.create(); if(options.localOffsetB){ vec2.copy(this.localOffsetB, options.localOffsetB); } else { // Construct from current positions vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); } /** * The offset angle of bodyB in bodyA's frame. * @property {Number} localAngleB */ this.localAngleB = 0; if(typeof(options.localAngleB) === 'number'){ this.localAngleB = options.localAngleB; } else { // Construct this.localAngleB = bodyB.angle - bodyA.angle; } this.equations.push(x, y, rot); this.setMaxForce(maxForce); } LockConstraint.prototype = new Constraint(); /** * Set the maximum force to be applied. * @method setMaxForce * @param {Number} force */ LockConstraint.prototype.setMaxForce = function(force){ var eqs = this.equations; for(var i=0; i<this.equations.length; i++){ eqs[i].maxForce = force; eqs[i].minForce = -force; } }; /** * Get the max force. * @method getMaxForce * @return {Number} */ LockConstraint.prototype.getMaxForce = function(){ return this.equations[0].maxForce; }; var l = vec2.create(); var r = vec2.create(); var t = vec2.create(); var xAxis = vec2.fromValues(1,0); var yAxis = vec2.fromValues(0,1); LockConstraint.prototype.update = function(){ var x = this.equations[0], y = this.equations[1], rot = this.equations[2], bodyA = this.bodyA, bodyB = this.bodyB; vec2.rotate(l,this.localOffsetB,bodyA.angle); vec2.rotate(r,this.localOffsetB,bodyB.angle - this.localAngleB); vec2.scale(r,r,-1); vec2.rotate(t,r,Math.PI/2); vec2.normalize(t,t); x.G[0] = -1; x.G[1] = 0; x.G[2] = -vec2.crossLength(l,xAxis); x.G[3] = 1; y.G[0] = 0; y.G[1] = -1; y.G[2] = -vec2.crossLength(l,yAxis); y.G[4] = 1; rot.G[0] = -t[0]; rot.G[1] = -t[1]; rot.G[3] = t[0]; rot.G[4] = t[1]; rot.G[5] = vec2.crossLength(r,t); }; },{"../equations/Equation":23,"../math/vec2":31,"./Constraint":15,"__browserify_Buffer":1,"__browserify_process":2}],19:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/constraints\\PrismaticConstraint.js",__dirname="/constraints";var Constraint = require('./Constraint') , ContactEquation = require('../equations/ContactEquation') , Equation = require('../equations/Equation') , vec2 = require('../math/vec2') , RotationalLockEquation = require('../equations/RotationalLockEquation'); module.exports = PrismaticConstraint; /** * Constraint that only allows bodies to move along a line, relative to each other. See <a href="http://www.iforce2d.net/b2dtut/joints-prismatic">this tutorial</a>. * * @class PrismaticConstraint * @constructor * @extends Constraint * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.maxForce] Max force to be applied by the constraint * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. * @param {Number} [options.upperLimit] * @param {Number} [options.lowerLimit] * @todo Ability to create using only a point and a worldAxis */ function PrismaticConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); // Get anchors var localAnchorA = vec2.fromValues(0,0), localAxisA = vec2.fromValues(1,0), localAnchorB = vec2.fromValues(0,0); if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } /** * @property localAnchorA * @type {Array} */ this.localAnchorA = localAnchorA; /** * @property localAnchorB * @type {Array} */ this.localAnchorB = localAnchorB; /** * @property localAxisA * @type {Array} */ this.localAxisA = localAxisA; /* The constraint violation for the common axis point is g = ( xj + rj - xi - ri ) * t := gg*t where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) Note the use of the chain rule. Now we identify the jacobian G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] The rotational part is just a rotation lock. */ var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; // Translational part var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); var ri = new vec2.create(), rj = new vec2.create(), gg = new vec2.create(), t = new vec2.create(); trans.computeGq = function(){ // g = ( xj + rj - xi - ri ) * t return vec2.dot(gg,t); }; trans.updateJacobian = function(){ var G = this.G, xi = bodyA.position, xj = bodyB.position; vec2.rotate(ri,localAnchorA,bodyA.angle); vec2.rotate(rj,localAnchorB,bodyB.angle); vec2.add(gg,xj,rj); vec2.sub(gg,gg,xi); vec2.sub(gg,gg,ri); vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); G[0] = -t[0]; G[1] = -t[1]; G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); G[3] = t[0]; G[4] = t[1]; G[5] = vec2.crossLength(rj,t); }; this.equations.push(trans); // Rotational part if(!options.disableRotationalLock){ var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); this.equations.push(rot); } /** * The position of anchor A relative to anchor B, along the constraint axis. * @property position * @type {Number} */ this.position = 0; // Is this one used at all? this.velocity = 0; /** * Set to true to enable lower limit. * @property lowerLimitEnabled * @type {Boolean} */ this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; /** * Set to true to enable upper limit. * @property upperLimitEnabled * @type {Boolean} */ this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; /** * Lower constraint limit. The constraint position is forced to be larger than this value. * @property lowerLimit * @type {Number} */ this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; /** * Upper constraint limit. The constraint position is forced to be smaller than this value. * @property upperLimit * @type {Number} */ this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; // Equations used for limits this.upperLimitEquation = new ContactEquation(bodyA,bodyB); this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); // Set max/min forces this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; /** * Equation used for the motor. * @property motorEquation * @type {Equation} */ this.motorEquation = new Equation(bodyA,bodyB); /** * The current motor state. Enable or disable the motor using .enableMotor * @property motorEnabled * @type {Boolean} */ this.motorEnabled = false; /** * Set the target speed for the motor. * @property motorSpeed * @type {Number} */ this.motorSpeed = 0; var that = this; var motorEquation = this.motorEquation; var old = motorEquation.computeGW; motorEquation.computeGq = function(){ return 0; }; motorEquation.computeGW = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.velocity, vj = bj.velocity, wi = bi.angularVelocity, wj = bj.angularVelocity; return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; }; } PrismaticConstraint.prototype = new Constraint(); var worldAxisA = vec2.create(), worldAnchorA = vec2.create(), worldAnchorB = vec2.create(), orientedAnchorA = vec2.create(), orientedAnchorB = vec2.create(), tmp = vec2.create(); /** * Update the constraint equations. Should be done if any of the bodies changed position, before solving. * @method update */ PrismaticConstraint.prototype.update = function(){ var eqs = this.equations, trans = eqs[0], upperLimit = this.upperLimit, lowerLimit = this.lowerLimit, upperLimitEquation = this.upperLimitEquation, lowerLimitEquation = this.lowerLimitEquation, bodyA = this.bodyA, bodyB = this.bodyB, localAxisA = this.localAxisA, localAnchorA = this.localAnchorA, localAnchorB = this.localAnchorB; trans.updateJacobian(); // Transform local things to world vec2.rotate(worldAxisA, localAxisA, bodyA.angle); vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); // Motor if(this.motorEnabled){ // G = [ a a x ri -a -a x rj ] var G = this.motorEquation.G; G[0] = worldAxisA[0]; G[1] = worldAxisA[1]; G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); G[3] = -worldAxisA[0]; G[4] = -worldAxisA[1]; G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); } /* Limits strategy: Add contact equation, with normal along the constraint axis. min/maxForce is set so the constraint is repulsive in the correct direction. Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. ^ | upperLimit x | ------ anchorB x<---| B | | | | ------ | ------ | | | | A |-->x anchorA ------ | x lowerLimit | axis */ if(this.upperLimitEnabled && relPosition > upperLimit){ // Update contact constraint normal, etc vec2.scale(upperLimitEquation.normalA, worldAxisA, -1); vec2.sub(upperLimitEquation.contactPointA, worldAnchorA, bodyA.position); vec2.sub(upperLimitEquation.contactPointB, worldAnchorB, bodyB.position); vec2.scale(tmp,worldAxisA,upperLimit); vec2.add(upperLimitEquation.contactPointA,upperLimitEquation.contactPointA,tmp); if(eqs.indexOf(upperLimitEquation) === -1){ eqs.push(upperLimitEquation); } } else { var idx = eqs.indexOf(upperLimitEquation); if(idx !== -1){ eqs.splice(idx,1); } } if(this.lowerLimitEnabled && relPosition < lowerLimit){ // Update contact constraint normal, etc vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); vec2.scale(tmp,worldAxisA,lowerLimit); vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); if(eqs.indexOf(lowerLimitEquation) === -1){ eqs.push(lowerLimitEquation); } } else { var idx = eqs.indexOf(lowerLimitEquation); if(idx !== -1){ eqs.splice(idx,1); } } }; /** * Enable the motor * @method enableMotor */ PrismaticConstraint.prototype.enableMotor = function(){ if(this.motorEnabled){ return; } this.equations.push(this.motorEquation); this.motorEnabled = true; }; /** * Disable the rotational motor * @method disableMotor */ PrismaticConstraint.prototype.disableMotor = function(){ if(!this.motorEnabled){ return; } var i = this.equations.indexOf(this.motorEquation); this.equations.splice(i,1); this.motorEnabled = false; }; /** * Set the constraint limits. * @method setLimits * @param {number} lower Lower limit. * @param {number} upper Upper limit. */ PrismaticConstraint.prototype.setLimits = function (lower, upper) { if(typeof(lower) === 'number'){ this.lowerLimit = lower; this.lowerLimitEnabled = true; } else { this.lowerLimit = lower; this.lowerLimitEnabled = false; } if(typeof(upper) === 'number'){ this.upperLimit = upper; this.upperLimitEnabled = true; } else { this.upperLimit = upper; this.upperLimitEnabled = false; } }; },{"../equations/ContactEquation":22,"../equations/Equation":23,"../equations/RotationalLockEquation":25,"../math/vec2":31,"./Constraint":15,"__browserify_Buffer":1,"__browserify_process":2}],20:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/constraints\\RevoluteConstraint.js",__dirname="/constraints";var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , RotationalVelocityEquation = require('../equations/RotationalVelocityEquation') , RotationalLockEquation = require('../equations/RotationalLockEquation') , vec2 = require('../math/vec2'); module.exports = RevoluteConstraint; var worldPivotA = vec2.create(), worldPivotB = vec2.create(), xAxis = vec2.fromValues(1,0), yAxis = vec2.fromValues(0,1), g = vec2.create(); /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * @class RevoluteConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. * @param {Array} [options.localPivotB] See localPivotA. * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. * @extends Constraint * * @example * // This will create a revolute constraint between two bodies with pivot point in between them. * var bodyA = new Body({ mass: 1, position: [-1, 0] }); * var bodyB = new Body({ mass: 1, position: [1, 0] }); * var constraint = new RevoluteConstraint(bodyA, bodyB, { * worldPivot: [0, 0] * }); * world.addConstraint(constraint); * * // Using body-local pivot points, the constraint could have been constructed like this: * var constraint = new RevoluteConstraint(bodyA, bodyB, { * localPivotA: [1, 0], * localPivotB: [-1, 0] * }); */ function RevoluteConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; /** * @property {Array} pivotA */ this.pivotA = vec2.create(); /** * @property {Array} pivotB */ this.pivotB = vec2.create(); if(options.worldPivot){ // Compute pivotA and pivotB vec2.sub(this.pivotA, options.worldPivot, bodyA.position); vec2.sub(this.pivotB, options.worldPivot, bodyB.position); // Rotate to local coordinate system vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); } else { // Get pivotA and pivotB vec2.copy(this.pivotA, options.localPivotA); vec2.copy(this.pivotB, options.localPivotB); } // Equations to be fed to the solver var eqs = this.equations = [ new Equation(bodyA,bodyB,-maxForce,maxForce), new Equation(bodyA,bodyB,-maxForce,maxForce), ]; var x = eqs[0]; var y = eqs[1]; var that = this; x.computeGq = function(){ vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); vec2.add(g, bodyB.position, worldPivotB); vec2.sub(g, g, bodyA.position); vec2.sub(g, g, worldPivotA); return vec2.dot(g,xAxis); }; y.computeGq = function(){ vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); vec2.add(g, bodyB.position, worldPivotB); vec2.sub(g, g, bodyA.position); vec2.sub(g, g, worldPivotA); return vec2.dot(g,yAxis); }; y.minForce = x.minForce = -maxForce; y.maxForce = x.maxForce = maxForce; this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); /** * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. * @property {Boolean} motorEnabled * @readOnly */ this.motorEnabled = false; /** * The constraint position. * @property angle * @type {Number} * @readOnly */ this.angle = 0; /** * Set to true to enable lower limit * @property lowerLimitEnabled * @type {Boolean} */ this.lowerLimitEnabled = false; /** * Set to true to enable upper limit * @property upperLimitEnabled * @type {Boolean} */ this.upperLimitEnabled = false; /** * The lower limit on the constraint angle. * @property lowerLimit * @type {Boolean} */ this.lowerLimit = 0; /** * The upper limit on the constraint angle. * @property upperLimit * @type {Boolean} */ this.upperLimit = 0; this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); this.upperLimitEquation.minForce = 0; this.lowerLimitEquation.maxForce = 0; } RevoluteConstraint.prototype = new Constraint(); /** * Set the constraint angle limits. * @method setLimits * @param {number} lower Lower angle limit. * @param {number} upper Upper angle limit. */ RevoluteConstraint.prototype.setLimits = function (lower, upper) { if(typeof(lower) === 'number'){ this.lowerLimit = lower; this.lowerLimitEnabled = true; } else { this.lowerLimit = lower; this.lowerLimitEnabled = false; } if(typeof(upper) === 'number'){ this.upperLimit = upper; this.upperLimitEnabled = true; } else { this.upperLimit = upper; this.upperLimitEnabled = false; } }; RevoluteConstraint.prototype.update = function(){ var bodyA = this.bodyA, bodyB = this.bodyB, pivotA = this.pivotA, pivotB = this.pivotB, eqs = this.equations, normal = eqs[0], tangent= eqs[1], x = eqs[0], y = eqs[1], upperLimit = this.upperLimit, lowerLimit = this.lowerLimit, upperLimitEquation = this.upperLimitEquation, lowerLimitEquation = this.lowerLimitEquation; var relAngle = this.angle = bodyB.angle - bodyA.angle; if(this.upperLimitEnabled && relAngle > upperLimit){ upperLimitEquation.angle = upperLimit; if(eqs.indexOf(upperLimitEquation) === -1){ eqs.push(upperLimitEquation); } } else { var idx = eqs.indexOf(upperLimitEquation); if(idx !== -1){ eqs.splice(idx,1); } } if(this.lowerLimitEnabled && relAngle < lowerLimit){ lowerLimitEquation.angle = lowerLimit; if(eqs.indexOf(lowerLimitEquation) === -1){ eqs.push(lowerLimitEquation); } } else { var idx = eqs.indexOf(lowerLimitEquation); if(idx !== -1){ eqs.splice(idx,1); } } /* The constraint violation is g = xj + rj - xi - ri ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: gdot = vj + wj x rj - vi - wi x ri We split this into x and y directions. (let x and y be unit vectors along the respective axes) gdot * x = ( vj + wj x rj - vi - wi x ri ) * x = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] = G*W ...and similar for y. We have then identified the jacobian entries for x and y directions: Gx = [ x (rj x x) -x -(ri x x)] Gy = [ y (rj x y) -y -(ri x y)] */ vec2.rotate(worldPivotA, pivotA, bodyA.angle); vec2.rotate(worldPivotB, pivotB, bodyB.angle); // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc x.G[0] = -1; x.G[1] = 0; x.G[2] = -vec2.crossLength(worldPivotA,xAxis); x.G[3] = 1; x.G[4] = 0; x.G[5] = vec2.crossLength(worldPivotB,xAxis); y.G[0] = 0; y.G[1] = -1; y.G[2] = -vec2.crossLength(worldPivotA,yAxis); y.G[3] = 0; y.G[4] = 1; y.G[5] = vec2.crossLength(worldPivotB,yAxis); }; /** * Enable the rotational motor * @method enableMotor */ RevoluteConstraint.prototype.enableMotor = function(){ if(this.motorEnabled){ return; } this.equations.push(this.motorEquation); this.motorEnabled = true; }; /** * Disable the rotational motor * @method disableMotor */ RevoluteConstraint.prototype.disableMotor = function(){ if(!this.motorEnabled){ return; } var i = this.equations.indexOf(this.motorEquation); this.equations.splice(i,1); this.motorEnabled = false; }; /** * Check if the motor is enabled. * @method motorIsEnabled * @deprecated use property motorEnabled instead. * @return {Boolean} */ RevoluteConstraint.prototype.motorIsEnabled = function(){ return !!this.motorEnabled; }; /** * Set the speed of the rotational constraint motor * @method setMotorSpeed * @param {Number} speed */ RevoluteConstraint.prototype.setMotorSpeed = function(speed){ if(!this.motorEnabled){ return; } var i = this.equations.indexOf(this.motorEquation); this.equations[i].relativeVelocity = speed; }; /** * Get the speed of the rotational constraint motor * @method getMotorSpeed * @return {Number} The current speed, or false if the motor is not enabled. */ RevoluteConstraint.prototype.getMotorSpeed = function(){ if(!this.motorEnabled){ return false; } return this.motorEquation.relativeVelocity; }; },{"../equations/Equation":23,"../equations/RotationalLockEquation":25,"../equations/RotationalVelocityEquation":26,"../math/vec2":31,"./Constraint":15,"__browserify_Buffer":1,"__browserify_process":2}],21:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/equations\\AngleLockEquation.js",__dirname="/equations";var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = AngleLockEquation; /** * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. * * @class AngleLockEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle] Angle to add to the local vector in body A. * @param {Number} [options.ratio] Gear ratio */ function AngleLockEquation(bodyA, bodyB, options){ options = options || {}; Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); this.angle = options.angle || 0; /** * The gear ratio. * @property {Number} ratio * @private * @see setRatio */ this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; this.setRatio(this.ratio); } AngleLockEquation.prototype = new Equation(); AngleLockEquation.prototype.constructor = AngleLockEquation; AngleLockEquation.prototype.computeGq = function(){ return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; }; /** * Set the gear ratio for this equation * @method setRatio * @param {Number} ratio */ AngleLockEquation.prototype.setRatio = function(ratio){ var G = this.G; G[2] = ratio; G[5] = -1; this.ratio = ratio; }; /** * Set the max force for the equation. * @method setMaxTorque * @param {Number} torque */ AngleLockEquation.prototype.setMaxTorque = function(torque){ this.maxForce = torque; this.minForce = -torque; }; },{"../math/vec2":31,"./Equation":23,"__browserify_Buffer":1,"__browserify_process":2}],22:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/equations\\ContactEquation.js",__dirname="/equations";var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = ContactEquation; /** * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. * * @class ContactEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB */ function ContactEquation(bodyA, bodyB){ Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); /** * Vector from body i center of mass to the contact point. * @property contactPointA * @type {Array} */ this.contactPointA = vec2.create(); this.penetrationVec = vec2.create(); /** * World-oriented vector from body A center of mass to the contact point. * @property contactPointB * @type {Array} */ this.contactPointB = vec2.create(); /** * The normal vector, pointing out of body i * @property normalA * @type {Array} */ this.normalA = vec2.create(); /** * The restitution to use (0=no bounciness, 1=max bounciness). * @property restitution * @type {Number} */ this.restitution = 0; /** * This property is set to true if this is the first impact between the bodies (not persistant contact). * @property firstImpact * @type {Boolean} * @readOnly */ this.firstImpact = false; /** * The shape in body i that triggered this contact. * @property shapeA * @type {Shape} */ this.shapeA = null; /** * The shape in body j that triggered this contact. * @property shapeB * @type {Shape} */ this.shapeB = null; } ContactEquation.prototype = new Equation(); ContactEquation.prototype.constructor = ContactEquation; ContactEquation.prototype.computeB = function(a,b,h){ var bi = this.bodyA, bj = this.bodyB, ri = this.contactPointA, rj = this.contactPointB, xi = bi.position, xj = bj.position; var penetrationVec = this.penetrationVec, n = this.normalA, G = this.G; // Caluclate cross products var rixn = vec2.crossLength(ri,n), rjxn = vec2.crossLength(rj,n); // G = [-n -rixn n rjxn] G[0] = -n[0]; G[1] = -n[1]; G[2] = -rixn; G[3] = n[0]; G[4] = n[1]; G[5] = rjxn; // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector vec2.add(penetrationVec,xj,rj); vec2.sub(penetrationVec,penetrationVec,xi); vec2.sub(penetrationVec,penetrationVec,ri); // Compute iteration var GW, Gq; if(this.firstImpact && this.restitution !== 0){ Gq = 0; GW = (1/b)*(1+this.restitution) * this.computeGW(); } else { Gq = vec2.dot(n,penetrationVec) + this.offset; GW = this.computeGW(); } var GiMf = this.computeGiMf(); var B = - Gq * a - GW * b - h*GiMf; return B; }; },{"../math/vec2":31,"./Equation":23,"__browserify_Buffer":1,"__browserify_process":2}],23:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/equations\\Equation.js",__dirname="/equations";module.exports = Equation; var vec2 = require('../math/vec2'), Utils = require('../utils/Utils'), Body = require('../objects/Body'); /** * Base class for constraint equations. * @class Equation * @constructor * @param {Body} bodyA First body participating in the equation * @param {Body} bodyB Second body participating in the equation * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE */ function Equation(bodyA, bodyB, minForce, maxForce){ /** * Minimum force to apply when solving. * @property minForce * @type {Number} */ this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; /** * Max force to apply when solving. * @property maxForce * @type {Number} */ this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; /** * First body participating in the constraint * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second body participating in the constraint * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. * @property stiffness * @type {Number} */ this.stiffness = Equation.DEFAULT_STIFFNESS; /** * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. * @property relaxation * @type {Number} */ this.relaxation = Equation.DEFAULT_RELAXATION; /** * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). * @property G * @type {Array} */ this.G = new Utils.ARRAY_TYPE(6); for(var i=0; i<6; i++){ this.G[i]=0; } this.offset = 0; this.a = 0; this.b = 0; this.epsilon = 0; this.timeStep = 1/60; /** * Indicates if stiffness or relaxation was changed. * @property {Boolean} needsUpdate */ this.needsUpdate = true; /** * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. * @property multiplier * @type {Number} */ this.multiplier = 0; /** * Relative velocity. * @property {Number} relativeVelocity */ this.relativeVelocity = 0; /** * Whether this equation is enabled or not. If true, it will be added to the solver. * @property {Boolean} enabled */ this.enabled = true; } Equation.prototype.constructor = Equation; /** * The default stiffness when creating a new Equation. * @static * @property {Number} DEFAULT_STIFFNESS * @default 1e6 */ Equation.DEFAULT_STIFFNESS = 1e6; /** * The default relaxation when creating a new Equation. * @static * @property {Number} DEFAULT_RELAXATION * @default 4 */ Equation.DEFAULT_RELAXATION = 4; /** * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the <a href="http://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf">SPOOK notes</a>. * @method update */ Equation.prototype.update = function(){ var k = this.stiffness, d = this.relaxation, h = this.timeStep; this.a = 4.0 / (h * (1 + 4 * d)); this.b = (4.0 * d) / (1 + 4 * d); this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); this.needsUpdate = false; }; /** * Multiply a jacobian entry with corresponding positions or velocities * @method gmult * @return {Number} */ Equation.prototype.gmult = function(G,vi,wi,vj,wj){ return G[0] * vi[0] + G[1] * vi[1] + G[2] * wi + G[3] * vj[0] + G[4] * vj[1] + G[5] * wj; }; /** * Computes the RHS of the SPOOK equation * @method computeB * @return {Number} */ Equation.prototype.computeB = function(a,b,h){ var GW = this.computeGW(); var Gq = this.computeGq(); var GiMf = this.computeGiMf(); return - Gq * a - GW * b - GiMf*h; }; /** * Computes G\*q, where q are the generalized body coordinates * @method computeGq * @return {Number} */ var qi = vec2.create(), qj = vec2.create(); Equation.prototype.computeGq = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, xi = bi.position, xj = bj.position, ai = bi.angle, aj = bj.angle; return this.gmult(G, qi, ai, qj, aj) + this.offset; }; /** * Computes G\*W, where W are the body velocities * @method computeGW * @return {Number} */ Equation.prototype.computeGW = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.velocity, vj = bj.velocity, wi = bi.angularVelocity, wj = bj.angularVelocity; return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; }; /** * Computes G\*Wlambda, where W are the body velocities * @method computeGWlambda * @return {Number} */ Equation.prototype.computeGWlambda = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.vlambda, vj = bj.vlambda, wi = bi.wlambda, wj = bj.wlambda; return this.gmult(G,vi,wi,vj,wj); }; /** * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. * @method computeGiMf * @return {Number} */ var iMfi = vec2.create(), iMfj = vec2.create(); Equation.prototype.computeGiMf = function(){ var bi = this.bodyA, bj = this.bodyB, fi = bi.force, ti = bi.angularForce, fj = bj.force, tj = bj.angularForce, invMassi = bi.invMassSolve, invMassj = bj.invMassSolve, invIi = bi.invInertiaSolve, invIj = bj.invInertiaSolve, G = this.G; vec2.scale(iMfi, fi,invMassi); vec2.scale(iMfj, fj,invMassj); return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); }; /** * Computes G\*inv(M)\*G' * @method computeGiMGt * @return {Number} */ Equation.prototype.computeGiMGt = function(){ var bi = this.bodyA, bj = this.bodyB, invMassi = bi.invMassSolve, invMassj = bj.invMassSolve, invIi = bi.invInertiaSolve, invIj = bj.invInertiaSolve, G = this.G; return G[0] * G[0] * invMassi + G[1] * G[1] * invMassi + G[2] * G[2] * invIi + G[3] * G[3] * invMassj + G[4] * G[4] * invMassj + G[5] * G[5] * invIj; }; var addToWlambda_temp = vec2.create(), addToWlambda_Gi = vec2.create(), addToWlambda_Gj = vec2.create(), addToWlambda_ri = vec2.create(), addToWlambda_rj = vec2.create(), addToWlambda_Mdiag = vec2.create(); /** * Add constraint velocity to the bodies. * @method addToWlambda * @param {Number} deltalambda */ Equation.prototype.addToWlambda = function(deltalambda){ var bi = this.bodyA, bj = this.bodyB, temp = addToWlambda_temp, Gi = addToWlambda_Gi, Gj = addToWlambda_Gj, ri = addToWlambda_ri, rj = addToWlambda_rj, invMassi = bi.invMassSolve, invMassj = bj.invMassSolve, invIi = bi.invInertiaSolve, invIj = bj.invInertiaSolve, Mdiag = addToWlambda_Mdiag, G = this.G; Gi[0] = G[0]; Gi[1] = G[1]; Gj[0] = G[3]; Gj[1] = G[4]; // Add to linear velocity // v_lambda += inv(M) * delta_lamba * G vec2.scale(temp, Gi, invMassi*deltalambda); vec2.add( bi.vlambda, bi.vlambda, temp); // This impulse is in the offset frame // Also add contribution to angular //bi.wlambda -= vec2.crossLength(temp,ri); bi.wlambda += invIi * G[2] * deltalambda; vec2.scale(temp, Gj, invMassj*deltalambda); vec2.add( bj.vlambda, bj.vlambda, temp); //bj.wlambda -= vec2.crossLength(temp,rj); bj.wlambda += invIj * G[5] * deltalambda; }; /** * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps * @method computeInvC * @param {Number} eps * @return {Number} */ Equation.prototype.computeInvC = function(eps){ return 1.0 / (this.computeGiMGt() + eps); }; },{"../math/vec2":31,"../objects/Body":32,"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],24:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/equations\\FrictionEquation.js",__dirname="/equations";var vec2 = require('../math/vec2') , Equation = require('./Equation') , Utils = require('../utils/Utils'); module.exports = FrictionEquation; /** * Constrains the slipping in a contact along a tangent * * @class FrictionEquation * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Number} slipForce * @extends Equation */ function FrictionEquation(bodyA, bodyB, slipForce){ Equation.call(this, bodyA, bodyB, -slipForce, slipForce); /** * Relative vector from center of body A to the contact point, world oriented. * @property contactPointA * @type {Array} */ this.contactPointA = vec2.create(); /** * Relative vector from center of body B to the contact point, world oriented. * @property contactPointB * @type {Array} */ this.contactPointB = vec2.create(); /** * Tangent vector that the friction force will act along. World oriented. * @property t * @type {Array} */ this.t = vec2.create(); /** * A ContactEquation connected to this friction. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. * @property contactEquations * @type {ContactEquation} */ this.contactEquations = []; /** * The shape in body i that triggered this friction. * @property shapeA * @type {Shape} * @todo Needed? The shape can be looked up via contactEquation.shapeA... */ this.shapeA = null; /** * The shape in body j that triggered this friction. * @property shapeB * @type {Shape} * @todo Needed? The shape can be looked up via contactEquation.shapeB... */ this.shapeB = null; /** * The friction coefficient to use. * @property frictionCoefficient * @type {Number} */ this.frictionCoefficient = 0.3; } FrictionEquation.prototype = new Equation(); FrictionEquation.prototype.constructor = FrictionEquation; /** * Set the slipping condition for the constraint. The friction force cannot be * larger than this value. * @method setSlipForce * @param {Number} slipForce */ FrictionEquation.prototype.setSlipForce = function(slipForce){ this.maxForce = slipForce; this.minForce = -slipForce; }; /** * Get the max force for the constraint. * @method getSlipForce * @return {Number} */ FrictionEquation.prototype.getSlipForce = function(){ return this.maxForce; }; FrictionEquation.prototype.computeB = function(a,b,h){ var bi = this.bodyA, bj = this.bodyB, ri = this.contactPointA, rj = this.contactPointB, t = this.t, G = this.G; // G = [-t -rixt t rjxt] // And remember, this is a pure velocity constraint, g is always zero! G[0] = -t[0]; G[1] = -t[1]; G[2] = -vec2.crossLength(ri,t); G[3] = t[0]; G[4] = t[1]; G[5] = vec2.crossLength(rj,t); var GW = this.computeGW(), GiMf = this.computeGiMf(); var B = /* - g * a */ - GW * b - h*GiMf; return B; }; },{"../math/vec2":31,"../utils/Utils":50,"./Equation":23,"__browserify_Buffer":1,"__browserify_process":2}],25:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/equations\\RotationalLockEquation.js",__dirname="/equations";var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = RotationalLockEquation; /** * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. * * @class RotationalLockEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle] Angle to add to the local vector in bodyA. */ function RotationalLockEquation(bodyA, bodyB, options){ options = options || {}; Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); /** * @property {number} angle */ this.angle = options.angle || 0; var G = this.G; G[2] = 1; G[5] = -1; } RotationalLockEquation.prototype = new Equation(); RotationalLockEquation.prototype.constructor = RotationalLockEquation; var worldVectorA = vec2.create(), worldVectorB = vec2.create(), xAxis = vec2.fromValues(1,0), yAxis = vec2.fromValues(0,1); RotationalLockEquation.prototype.computeGq = function(){ vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); return vec2.dot(worldVectorA,worldVectorB); }; },{"../math/vec2":31,"./Equation":23,"__browserify_Buffer":1,"__browserify_process":2}],26:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/equations\\RotationalVelocityEquation.js",__dirname="/equations";var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = RotationalVelocityEquation; /** * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). * * @class RotationalVelocityEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB */ function RotationalVelocityEquation(bodyA, bodyB){ Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); this.relativeVelocity = 1; this.ratio = 1; } RotationalVelocityEquation.prototype = new Equation(); RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; RotationalVelocityEquation.prototype.computeB = function(a,b,h){ var G = this.G; G[2] = -1; G[5] = this.ratio; var GiMf = this.computeGiMf(); var GW = this.computeGW(); var B = - GW * b - h*GiMf; return B; }; },{"../math/vec2":31,"./Equation":23,"__browserify_Buffer":1,"__browserify_process":2}],27:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/events\\EventEmitter.js",__dirname="/events";/** * Base class for objects that dispatches events. * @class EventEmitter * @constructor */ var EventEmitter = function () {}; module.exports = EventEmitter; EventEmitter.prototype = { constructor: EventEmitter, /** * Add an event listener * @method on * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. */ on: function ( type, listener, context ) { listener.context = context || this; if ( this._listeners === undefined ){ this._listeners = {}; } var listeners = this._listeners; if ( listeners[ type ] === undefined ) { listeners[ type ] = []; } if ( listeners[ type ].indexOf( listener ) === - 1 ) { listeners[ type ].push( listener ); } return this; }, /** * Check if an event listener is added * @method has * @param {String} type * @param {Function} listener * @return {Boolean} */ has: function ( type, listener ) { if ( this._listeners === undefined ){ return false; } var listeners = this._listeners; if(listener){ if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { return true; } } else { if ( listeners[ type ] !== undefined ) { return true; } } return false; }, /** * Remove an event listener * @method off * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. */ off: function ( type, listener ) { if ( this._listeners === undefined ){ return this; } var listeners = this._listeners; var index = listeners[ type ].indexOf( listener ); if ( index !== - 1 ) { listeners[ type ].splice( index, 1 ); } return this; }, /** * Emit an event. * @method emit * @param {Object} event * @param {String} event.type * @return {EventEmitter} The self object, for chainability. */ emit: function ( event ) { if ( this._listeners === undefined ){ return this; } var listeners = this._listeners; var listenerArray = listeners[ event.type ]; if ( listenerArray !== undefined ) { event.target = this; for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { var listener = listenerArray[ i ]; listener.call( listener.context, event ); } } return this; } }; },{"__browserify_Buffer":1,"__browserify_process":2}],28:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/material\\ContactMaterial.js",__dirname="/material";var Material = require('./Material'); var Equation = require('../equations/Equation'); module.exports = ContactMaterial; /** * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. * @class ContactMaterial * @constructor * @param {Material} materialA * @param {Material} materialB * @param {Object} [options] * @param {Number} [options.friction=0.3] Friction coefficient. * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". * @param {Number} [options.stiffness] ContactEquation stiffness. * @param {Number} [options.relaxation] ContactEquation relaxation. * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. * @param {Number} [options.surfaceVelocity=0] Surface velocity. * @author schteppe */ function ContactMaterial(materialA, materialB, options){ options = options || {}; if(!(materialA instanceof Material) || !(materialB instanceof Material)){ throw new Error("First two arguments must be Material instances."); } /** * The contact material identifier * @property id * @type {Number} */ this.id = ContactMaterial.idCounter++; /** * First material participating in the contact material * @property materialA * @type {Material} */ this.materialA = materialA; /** * Second material participating in the contact material * @property materialB * @type {Material} */ this.materialB = materialB; /** * Friction to use in the contact of these two materials * @property friction * @type {Number} */ this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; /** * Restitution to use in the contact of these two materials * @property restitution * @type {Number} */ this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0.0; /** * Stiffness of the resulting ContactEquation that this ContactMaterial generate * @property stiffness * @type {Number} */ this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; /** * Relaxation of the resulting ContactEquation that this ContactMaterial generate * @property relaxation * @type {Number} */ this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; /** * Stiffness of the resulting FrictionEquation that this ContactMaterial generate * @property frictionStiffness * @type {Number} */ this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; /** * Relaxation of the resulting FrictionEquation that this ContactMaterial generate * @property frictionRelaxation * @type {Number} */ this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; /** * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. * @property {Number} surfaceVelocity */ this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; /** * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". * @property contactSkinSize * @type {Number} */ this.contactSkinSize = 0.005; } ContactMaterial.idCounter = 0; },{"../equations/Equation":23,"./Material":29,"__browserify_Buffer":1,"__browserify_process":2}],29:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/material\\Material.js",__dirname="/material";module.exports = Material; /** * Defines a physics material. * @class Material * @constructor * @param {number} id Material identifier * @author schteppe */ function Material(id){ /** * The material identifier * @property id * @type {Number} */ this.id = id || Material.idCounter++; } Material.idCounter = 0; },{"__browserify_Buffer":1,"__browserify_process":2}],30:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/math\\polyk.js",__dirname="/math"; /* PolyK library url: http://polyk.ivank.net Released under MIT licence. Copyright (c) 2012 Ivan Kuckir Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var PolyK = {}; /* Is Polygon self-intersecting? O(n^2) */ /* PolyK.IsSimple = function(p) { var n = p.length>>1; if(n<4) return true; var a1 = new PolyK._P(), a2 = new PolyK._P(); var b1 = new PolyK._P(), b2 = new PolyK._P(); var c = new PolyK._P(); for(var i=0; i<n; i++) { a1.x = p[2*i ]; a1.y = p[2*i+1]; if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; } else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; } for(var j=0; j<n; j++) { if(Math.abs(i-j) < 2) continue; if(j==n-1 && i==0) continue; if(i==n-1 && j==0) continue; b1.x = p[2*j ]; b1.y = p[2*j+1]; if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; } else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; } if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false; } } return true; } PolyK.IsConvex = function(p) { if(p.length<6) return true; var l = p.length - 4; for(var i=0; i<l; i+=2) if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false; if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false; if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false; return true; } */ PolyK.GetArea = function(p) { if(p.length <6) return 0; var l = p.length - 2; var sum = 0; for(var i=0; i<l; i+=2) sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]); sum += (p[0]-p[l]) * (p[l+1]+p[1]); return - sum * 0.5; } /* PolyK.GetAABB = function(p) { var minx = Infinity; var miny = Infinity; var maxx = -minx; var maxy = -miny; for(var i=0; i<p.length; i+=2) { minx = Math.min(minx, p[i ]); maxx = Math.max(maxx, p[i ]); miny = Math.min(miny, p[i+1]); maxy = Math.max(maxy, p[i+1]); } return {x:minx, y:miny, width:maxx-minx, height:maxy-miny}; } */ PolyK.Triangulate = function(p) { var n = p.length>>1; if(n<3) return []; var tgs = []; var avl = []; for(var i=0; i<n; i++) avl.push(i); var i = 0; var al = n; while(al > 3) { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; var ax = p[2*i0], ay = p[2*i0+1]; var bx = p[2*i1], by = p[2*i1+1]; var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; if(PolyK._convex(ax, ay, bx, by, cx, cy)) { earFound = true; for(var j=0; j<al; j++) { var vi = avl[j]; if(vi==i0 || vi==i1 || vi==i2) continue; if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;} } } if(earFound) { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i= 0; } else if(i++ > 3*al) break; // no convex angles :( } tgs.push(avl[0], avl[1], avl[2]); return tgs; } /* PolyK.ContainsPoint = function(p, px, py) { var n = p.length>>1; var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; var depth = 0; for(var i=0; i<n; i++) { ax = bx; ay = by; bx = p[2*i ] - px; by = p[2*i+1] - py; if(ay< 0 && by< 0) continue; // both "up" or both "donw" if(ay>=0 && by>=0) continue; // both "up" or both "donw" if(ax< 0 && bx< 0) continue; var lx = ax + (bx-ax)*(-ay)/(by-ay); if(lx>0) depth++; } return (depth & 1) == 1; } PolyK.Slice = function(p, ax, ay, bx, by) { if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; var a = new PolyK._P(ax, ay); var b = new PolyK._P(bx, by); var iscs = []; // intersections var ps = []; // points for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1])); for(var i=0; i<ps.length; i++) { var isc = new PolyK._P(0,0); isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc); if(isc) { isc.flag = true; iscs.push(isc); ps.splice(i+1,0,isc); i++; } } if(iscs.length == 0) return [p.slice(0)]; var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); } iscs.sort(comp); var pgs = []; var dir = 0; while(iscs.length > 0) { var n = ps.length; var i0 = iscs[0]; var i1 = iscs[1]; var ind0 = ps.indexOf(i0); var ind1 = ps.indexOf(i1); var solved = false; if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; else { i0 = iscs[1]; i1 = iscs[0]; ind0 = ps.indexOf(i0); ind1 = ps.indexOf(i1); if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; } if(solved) { dir--; var pgn = PolyK._getPoints(ps, ind0, ind1); pgs.push(pgn); ps = PolyK._getPoints(ps, ind1, ind0); i0.flag = i1.flag = false; iscs.splice(0,2); if(iscs.length == 0) pgs.push(ps); } else { dir++; iscs.reverse(); } if(dir>1) break; } var result = []; for(var i=0; i<pgs.length; i++) { var pg = pgs[i]; var npg = []; for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y); result.push(npg); } return result; } PolyK.Raycast = function(p, x, y, dx, dy, isc) { var l = p.length - 2; var tp = PolyK._tp; var a1 = tp[0], a2 = tp[1], b1 = tp[2], b2 = tp[3], c = tp[4]; a1.x = x; a1.y = y; a2.x = x+dx; a2.y = y+dy; if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}}; isc.dist = Infinity; for(var i=0; i<l; i+=2) { b1.x = p[i ]; b1.y = p[i+1]; b2.x = p[i+2]; b2.y = p[i+3]; var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c); if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc); } b1.x = b2.x; b1.y = b2.y; b2.x = p[0]; b2.y = p[1]; var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c); if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc); return (isc.dist != Infinity) ? isc : null; } PolyK.ClosestEdge = function(p, x, y, isc) { var l = p.length - 2; var tp = PolyK._tp; var a1 = tp[0], b1 = tp[2], b2 = tp[3], c = tp[4]; a1.x = x; a1.y = y; if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}}; isc.dist = Infinity; for(var i=0; i<l; i+=2) { b1.x = p[i ]; b1.y = p[i+1]; b2.x = p[i+2]; b2.y = p[i+3]; PolyK._pointLineDist(a1, b1, b2, i>>1, isc); } b1.x = b2.x; b1.y = b2.y; b2.x = p[0]; b2.y = p[1]; PolyK._pointLineDist(a1, b1, b2, l>>1, isc); var idst = 1/isc.dist; isc.norm.x = (x-isc.point.x)*idst; isc.norm.y = (y-isc.point.y)*idst; return isc; } PolyK._pointLineDist = function(p, a, b, edge, isc) { var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; var A = x - x1; var B = y - y1; var C = x2 - x1; var D = y2 - y1; var dot = A * C + B * D; var len_sq = C * C + D * D; var param = dot / len_sq; var xx, yy; if (param < 0 || (x1 == x2 && y1 == y2)) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * C; yy = y1 + param * D; } var dx = x - xx; var dy = y - yy; var dst = Math.sqrt(dx * dx + dy * dy); if(dst<isc.dist) { isc.dist = dst; isc.edge = edge; isc.point.x = xx; isc.point.y = yy; } } PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc) { var nrl = PolyK._P.dist(a1, c); if(nrl<isc.dist) { var ibl = 1/PolyK._P.dist(b1, b2); var nx = -(b2.y-b1.y)*ibl; var ny = (b2.x-b1.x)*ibl; var ddot = 2*(dx*nx+dy*ny); isc.dist = nrl; isc.norm.x = nx; isc.norm.y = ny; isc.refl.x = -ddot*nx+dx; isc.refl.y = -ddot*ny+dy; isc.edge = edge; } } PolyK._getPoints = function(ps, ind0, ind1) { var n = ps.length; var nps = []; if(ind1<ind0) ind1 += n; for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]); return nps; } PolyK._firstWithFlag = function(ps, ind) { var n = ps.length; while(true) { ind = (ind+1)%n; if(ps[ind].flag) return ind; } } */ PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy) { var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; var v1y = by-ay; var v2x = px-ax; var v2y = py-ay; var dot00 = v0x*v0x+v0y*v0y; var dot01 = v0x*v1x+v0y*v1y; var dot02 = v0x*v2x+v0y*v2y; var dot11 = v1x*v1x+v1y*v1y; var dot12 = v1x*v2x+v1y*v2y; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // Check if point is in triangle return (u >= 0) && (v >= 0) && (u + v < 1); } /* PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) { var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); var day = (a1.y-a2.y), dby = (b1.y-b2.y); var Den = dax*dby - day*dbx; if (Den == 0) return null; // parallel var A = (a1.x * a2.y - a1.y * a2.x); var B = (b1.x * b2.y - b1.y * b2.x); var I = c; var iDen = 1/Den; I.x = ( A*dbx - dax*B ) * iDen; I.y = ( A*dby - day*B ) * iDen; if(!PolyK._InRect(I, b1, b2)) return null; if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null; if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null; return I; } PolyK._GetLineIntersection = function(a1, a2, b1, b2, c) { var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); var day = (a1.y-a2.y), dby = (b1.y-b2.y); var Den = dax*dby - day*dbx; if (Den == 0) return null; // parallel var A = (a1.x * a2.y - a1.y * a2.x); var B = (b1.x * b2.y - b1.y * b2.x); var I = c; I.x = ( A*dbx - dax*B ) / Den; I.y = ( A*dby - day*B ) / Den; if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I; return null; } PolyK._InRect = function(a, b, c) { if (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) return true; return false; } */ PolyK._convex = function(ax, ay, bx, by, cx, cy) { return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; } /* PolyK._P = function(x,y) { this.x = x; this.y = y; this.flag = false; } PolyK._P.prototype.toString = function() { return "Point ["+this.x+", "+this.y+"]"; } PolyK._P.dist = function(a,b) { var dx = b.x-a.x; var dy = b.y-a.y; return Math.sqrt(dx*dx + dy*dy); } PolyK._tp = []; for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); */ module.exports = PolyK; },{"__browserify_Buffer":1,"__browserify_process":2}],31:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/math\\vec2.js",__dirname="/math";/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. * @class vec2 */ var vec2 = module.exports = {}; var Utils = require('../utils/Utils'); /** * Make a cross product and only return the z component * @method crossLength * @static * @param {Array} a * @param {Array} b * @return {Number} */ vec2.crossLength = function(a,b){ return a[0] * b[1] - a[1] * b[0]; }; /** * Cross product between a vector and the Z component of a vector * @method crossVZ * @static * @param {Array} out * @param {Array} vec * @param {Number} zcomp * @return {Number} */ vec2.crossVZ = function(out, vec, zcomp){ vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Cross product between a vector and the Z component of a vector * @method crossZV * @static * @param {Array} out * @param {Number} zcomp * @param {Array} vec * @return {Number} */ vec2.crossZV = function(out, zcomp, vec){ vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Rotate a vector by an angle * @method rotate * @static * @param {Array} out * @param {Array} a * @param {Number} angle */ vec2.rotate = function(out,a,angle){ if(angle !== 0){ var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; } else { out[0] = a[0]; out[1] = a[1]; } }; /** * Rotate a vector 90 degrees clockwise * @method rotate90cw * @static * @param {Array} out * @param {Array} a * @param {Number} angle */ vec2.rotate90cw = function(out, a) { var x = a[0]; var y = a[1]; out[0] = y; out[1] = -x; }; /** * Transform a point position to local frame. * @method toLocalFrame * @param {Array} out * @param {Array} worldPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ vec2.copy(out, worldPoint); vec2.sub(out, out, framePosition); vec2.rotate(out, out, -frameAngle); }; /** * Transform a point position to global frame. * @method toGlobalFrame * @param {Array} out * @param {Array} localPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ vec2.copy(out, localPoint); vec2.rotate(out, out, frameAngle); vec2.add(out, out, framePosition); }; /** * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php * @method centroid * @static * @param {Array} out * @param {Array} a * @param {Array} b * @param {Array} c * @return {Array} The out object */ vec2.centroid = function(out, a, b, c){ vec2.add(out, a, b); vec2.add(out, out, c); vec2.scale(out, out, 1/3); return out; }; /** * Creates a new, empty vec2 * @static * @method create * @return {Array} a new 2D vector */ vec2.create = function() { var out = new Utils.ARRAY_TYPE(2); out[0] = 0; out[1] = 0; return out; }; /** * Creates a new vec2 initialized with values from an existing vector * @static * @method clone * @param {Array} a vector to clone * @return {Array} a new 2D vector */ vec2.clone = function(a) { var out = new Utils.ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; }; /** * Creates a new vec2 initialized with the given values * @static * @method fromValues * @param {Number} x X component * @param {Number} y Y component * @return {Array} a new 2D vector */ vec2.fromValues = function(x, y) { var out = new Utils.ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; }; /** * Copy the values from one vec2 to another * @static * @method copy * @param {Array} out the receiving vector * @param {Array} a the source vector * @return {Array} out */ vec2.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out; }; /** * Set the components of a vec2 to the given values * @static * @method set * @param {Array} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @return {Array} out */ vec2.set = function(out, x, y) { out[0] = x; out[1] = y; return out; }; /** * Adds two vec2's * @static * @method add * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.add = function(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; }; /** * Subtracts two vec2's * @static * @method subtract * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.subtract = function(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; }; /** * Alias for vec2.subtract * @static * @method sub */ vec2.sub = vec2.subtract; /** * Multiplies two vec2's * @static * @method multiply * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.multiply = function(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; }; /** * Alias for vec2.multiply * @static * @method mul */ vec2.mul = vec2.multiply; /** * Divides two vec2's * @static * @method divide * @param {Array} out the receiving vector * @param {Array} a the first operand * @param {Array} b the second operand * @return {Array} out */ vec2.divide = function(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; }; /** * Alias for vec2.divide * @static * @method div */ vec2.div = vec2.divide; /** * Scales a vec2 by a scalar number * @static * @method scale * @param {Array} out the receiving vector * @param {Array} a the vector to scale * @param {Number} b amount to scale the vector by * @return {Array} out */ vec2.scale = function(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; }; /** * Calculates the euclidian distance between two vec2's * @static * @method distance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} distance between a and b */ vec2.distance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x*x + y*y); }; /** * Alias for vec2.distance * @static * @method dist */ vec2.dist = vec2.distance; /** * Calculates the squared euclidian distance between two vec2's * @static * @method squaredDistance * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} squared distance between a and b */ vec2.squaredDistance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x*x + y*y; }; /** * Alias for vec2.squaredDistance * @static * @method sqrDist */ vec2.sqrDist = vec2.squaredDistance; /** * Calculates the length of a vec2 * @static * @method length * @param {Array} a vector to calculate length of * @return {Number} length of a */ vec2.length = function (a) { var x = a[0], y = a[1]; return Math.sqrt(x*x + y*y); }; /** * Alias for vec2.length * @method len * @static */ vec2.len = vec2.length; /** * Calculates the squared length of a vec2 * @static * @method squaredLength * @param {Array} a vector to calculate squared length of * @return {Number} squared length of a */ vec2.squaredLength = function (a) { var x = a[0], y = a[1]; return x*x + y*y; }; /** * Alias for vec2.squaredLength * @static * @method sqrLen */ vec2.sqrLen = vec2.squaredLength; /** * Negates the components of a vec2 * @static * @method negate * @param {Array} out the receiving vector * @param {Array} a vector to negate * @return {Array} out */ vec2.negate = function(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; }; /** * Normalize a vec2 * @static * @method normalize * @param {Array} out the receiving vector * @param {Array} a vector to normalize * @return {Array} out */ vec2.normalize = function(out, a) { var x = a[0], y = a[1]; var len = x*x + y*y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; }; /** * Calculates the dot product of two vec2's * @static * @method dot * @param {Array} a the first operand * @param {Array} b the second operand * @return {Number} dot product of a and b */ vec2.dot = function (a, b) { return a[0] * b[0] + a[1] * b[1]; }; /** * Returns a string representation of a vector * @static * @method str * @param {Array} vec vector to represent as a string * @return {String} string representation of the vector */ vec2.str = function (a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; }; },{"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],32:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/objects\\Body.js",__dirname="/objects";var vec2 = require('../math/vec2') , decomp = require('poly-decomp') , Convex = require('../shapes/Convex') , AABB = require('../collision/AABB') , EventEmitter = require('../events/EventEmitter'); module.exports = Body; /** * A rigid body. Has got a center of mass, position, velocity and a number of * shapes that are used for collisions. * * @class Body * @constructor * @extends EventEmitter * @param {Object} [options] * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. * @param {Array} [options.position] * @param {Array} [options.velocity] * @param {Number} [options.angle=0] * @param {Number} [options.angularVelocity=0] * @param {Array} [options.force] * @param {Number} [options.angularForce=0] * @param {Number} [options.fixedRotation=false] * * @example * // Create a typical dynamic body * var body = new Body({ * mass: 1, * position: [0, 0], * angle: 0, * velocity: [0, 0], * angularVelocity: 0 * }); * * // Add a circular shape to the body * body.addShape(new Circle(1)); * * // Add the body to the world * world.addBody(body); */ function Body(options){ options = options || {}; EventEmitter.call(this); /** * The body identifyer * @property id * @type {Number} */ this.id = ++Body._idCounter; /** * The world that this body is added to. This property is set to NULL if the body is not added to any world. * @property world * @type {World} */ this.world = null; /** * The shapes of the body. The local transform of the shape in .shapes[i] is * defined by .shapeOffsets[i] and .shapeAngles[i]. * * @property shapes * @type {Array} */ this.shapes = []; /** * The local shape offsets, relative to the body center of mass. This is an * array of Array. * @property shapeOffsets * @type {Array} */ this.shapeOffsets = []; /** * The body-local shape angle transforms. This is an array of numbers (angles). * @property shapeAngles * @type {Array} */ this.shapeAngles = []; /** * The mass of the body. * @property mass * @type {number} */ this.mass = options.mass || 0; /** * The inverse mass of the body. * @property invMass * @type {number} */ this.invMass = 0; /** * The inertia of the body around the Z axis. * @property inertia * @type {number} */ this.inertia = 0; /** * The inverse inertia of the body. * @property invInertia * @type {number} */ this.invInertia = 0; this.invMassSolve = 0; this.invInertiaSolve = 0; /** * Set to true if you want to fix the rotation of the body. * @property fixedRotation * @type {Boolean} */ this.fixedRotation = !!options.fixedRotation; /** * The position of the body * @property position * @type {Array} */ this.position = vec2.fromValues(0,0); if(options.position){ vec2.copy(this.position, options.position); } /** * The interpolated position of the body. * @property interpolatedPosition * @type {Array} */ this.interpolatedPosition = vec2.fromValues(0,0); /** * The interpolated angle of the body. * @property interpolatedAngle * @type {Number} */ this.interpolatedAngle = 0; /** * The previous position of the body. * @property previousPosition * @type {Array} */ this.previousPosition = vec2.fromValues(0,0); /** * The previous angle of the body. * @property previousAngle * @type {Number} */ this.previousAngle = 0; /** * The velocity of the body * @property velocity * @type {Array} */ this.velocity = vec2.fromValues(0,0); if(options.velocity){ vec2.copy(this.velocity, options.velocity); } /** * Constraint velocity that was added to the body during the last step. * @property vlambda * @type {Array} */ this.vlambda = vec2.fromValues(0,0); /** * Angular constraint velocity that was added to the body during last step. * @property wlambda * @type {Array} */ this.wlambda = 0; /** * The angle of the body, in radians. * @property angle * @type {number} * @example * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. * // If you need a value between 0 and 2*pi, use the following function to normalize it. * function normalizeAngle(angle){ * angle = angle % (2*Math.PI); * if(angle < 0){ * angle += (2*Math.PI); * } * return angle; * } */ this.angle = options.angle || 0; /** * The angular velocity of the body, in radians per second. * @property angularVelocity * @type {number} */ this.angularVelocity = options.angularVelocity || 0; /** * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. * @property force * @type {Array} * * @example * // This produces a forcefield of 1 Newton in the positive x direction. * for(var i=0; i<numSteps; i++){ * body.force[0] = 1; * world.step(1/60); * } * * @example * // This will apply a rotational force on the body * for(var i=0; i<numSteps; i++){ * body.angularForce = -3; * world.step(1/60); * } */ this.force = vec2.create(); if(options.force){ vec2.copy(this.force, options.force); } /** * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}. * @property angularForce * @type {number} */ this.angularForce = options.angularForce || 0; /** * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1. * @property damping * @type {Number} * @default 0.1 */ this.damping = typeof(options.damping) === "number" ? options.damping : 0.1; /** * The angular force acting on the body. Should be a value between 0 and 1. * @property angularDamping * @type {Number} * @default 0.1 */ this.angularDamping = typeof(options.angularDamping) === "number" ? options.angularDamping : 0.1; /** * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}. * * * Static bodies do not move, and they do not respond to forces or collision. * * Dynamic bodies body can move and respond to collisions and forces. * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. * * @property type * @type {number} * * @example * // Bodies are static by default. Static bodies will never move. * var body = new Body(); * console.log(body.type == Body.STATIC); // true * * @example * // By setting the mass of a body to a nonzero number, the body * // will become dynamic and will move and interact with other bodies. * var dynamicBody = new Body({ * mass : 1 * }); * console.log(dynamicBody.type == Body.DYNAMIC); // true * * @example * // Kinematic bodies will only move if you change their velocity. * var kinematicBody = new Body({ * type: Body.KINEMATIC // Type can be set via the options object. * }); */ this.type = Body.STATIC; if(typeof(options.type) !== 'undefined'){ this.type = options.type; } else if(!options.mass){ this.type = Body.STATIC; } else { this.type = Body.DYNAMIC; } /** * Bounding circle radius. * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Bounding box of this body. * @property aabb * @type {AABB} */ this.aabb = new AABB(); /** * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}. * @property aabbNeedsUpdate * @type {Boolean} * @see updateAABB * * @example * // Force update the AABB * body.aabbNeedsUpdate = true; * body.updateAABB(); * console.log(body.aabbNeedsUpdate); // false */ this.aabbNeedsUpdate = true; /** * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen. * @property allowSleep * @type {Boolean} * @default true */ this.allowSleep = true; this.wantsToSleep = false; /** * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}. * * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY). * * @property sleepState * @type {Number} * @default Body.AWAKE */ this.sleepState = Body.AWAKE; /** * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy. * @property sleepSpeedLimit * @type {Number} * @default 0.2 */ this.sleepSpeedLimit = 0.2; /** * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping. * @property sleepTimeLimit * @type {Number} * @default 1 */ this.sleepTimeLimit = 1; /** * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1. * @property {Number} gravityScale * @default 1 */ this.gravityScale = 1; /** * The last time when the body went to SLEEPY state. * @property {Number} timeLastSleepy * @private */ this.timeLastSleepy = 0; this.concavePath = null; this._wakeUpAfterNarrowphase = false; this.updateMassProperties(); } Body.prototype = new EventEmitter(); Body._idCounter = 0; Body.prototype.updateSolveMassProperties = function(){ if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){ this.invMassSolve = 0; this.invInertiaSolve = 0; } else { this.invMassSolve = this.invMass; this.invInertiaSolve = this.invInertia; } }; /** * Set the total density of the body * @method setDensity */ Body.prototype.setDensity = function(density) { var totalArea = this.getArea(); this.mass = totalArea * density; this.updateMassProperties(); }; /** * Get the total area of all shapes in the body * @method getArea * @return {Number} */ Body.prototype.getArea = function() { var totalArea = 0; for(var i=0; i<this.shapes.length; i++){ totalArea += this.shapes[i].area; } return totalArea; }; /** * Get the AABB from the body. The AABB is updated if necessary. * @method getAABB */ Body.prototype.getAABB = function(){ if(this.aabbNeedsUpdate){ this.updateAABB(); } return this.aabb; }; var shapeAABB = new AABB(), tmp = vec2.create(); /** * Updates the AABB of the Body * @method updateAABB */ Body.prototype.updateAABB = function() { var shapes = this.shapes, shapeOffsets = this.shapeOffsets, shapeAngles = this.shapeAngles, N = shapes.length, offset = tmp, bodyAngle = this.angle; for(var i=0; i!==N; i++){ var shape = shapes[i], angle = shapeAngles[i] + bodyAngle; // Get shape world offset vec2.rotate(offset, shapeOffsets[i], bodyAngle); vec2.add(offset, offset, this.position); // Get shape AABB shape.computeAABB(shapeAABB, offset, angle); if(i===0){ this.aabb.copy(shapeAABB); } else { this.aabb.extend(shapeAABB); } } this.aabbNeedsUpdate = false; }; /** * Update the bounding radius of the body. Should be done if any of the shapes * are changed. * @method updateBoundingRadius */ Body.prototype.updateBoundingRadius = function(){ var shapes = this.shapes, shapeOffsets = this.shapeOffsets, N = shapes.length, radius = 0; for(var i=0; i!==N; i++){ var shape = shapes[i], offset = vec2.length(shapeOffsets[i]), r = shape.boundingRadius; if(offset + r > radius){ radius = offset + r; } } this.boundingRadius = radius; }; /** * Add a shape to the body. You can pass a local transform when adding a shape, * so that the shape gets an offset and angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method addShape * @param {Shape} shape * @param {Array} [offset] Local body offset of the shape. * @param {Number} [angle] Local body angle. * * @example * var body = new Body(), * shape = new Circle(); * * // Add the shape to the body, positioned in the center * body.addShape(shape); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. * body.addShape(shape,[1,0]); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. * body.addShape(shape,[0,1],Math.PI/2); */ Body.prototype.addShape = function(shape,offset,angle){ angle = angle || 0.0; // Copy the offset vector if(offset){ offset = vec2.fromValues(offset[0],offset[1]); } else { offset = vec2.fromValues(0,0); } this.shapes .push(shape); this.shapeOffsets.push(offset); this.shapeAngles .push(angle); this.updateMassProperties(); this.updateBoundingRadius(); this.aabbNeedsUpdate = true; }; /** * Remove a shape * @method removeShape * @param {Shape} shape * @return {Boolean} True if the shape was found and removed, else false. */ Body.prototype.removeShape = function(shape){ var idx = this.shapes.indexOf(shape); if(idx !== -1){ this.shapes.splice(idx,1); this.shapeOffsets.splice(idx,1); this.shapeAngles.splice(idx,1); this.aabbNeedsUpdate = true; return true; } else { return false; } }; /** * Updates .inertia, .invMass, .invInertia for this Body. Should be called when * changing the structure or mass of the Body. * * @method updateMassProperties * * @example * body.mass += 1; * body.updateMassProperties(); */ Body.prototype.updateMassProperties = function(){ if(this.type === Body.STATIC || this.type === Body.KINEMATIC){ this.mass = Number.MAX_VALUE; this.invMass = 0; this.inertia = Number.MAX_VALUE; this.invInertia = 0; } else { var shapes = this.shapes, N = shapes.length, m = this.mass / N, I = 0; if(!this.fixedRotation){ for(var i=0; i<N; i++){ var shape = shapes[i], r2 = vec2.squaredLength(this.shapeOffsets[i]), Icm = shape.computeMomentOfInertia(m); I += Icm + m*r2; } this.inertia = I; this.invInertia = I>0 ? 1/I : 0; } else { this.inertia = Number.MAX_VALUE; this.invInertia = 0; } // Inverse mass properties are easy this.invMass = 1/this.mass;// > 0 ? 1/this.mass : 0; } }; var Body_applyForce_r = vec2.create(); /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * @method applyForce * @param {Array} force The force to add. * @param {Array} worldPoint A world point to apply the force on. */ Body.prototype.applyForce = function(force,worldPoint){ // Compute point position relative to the body center var r = Body_applyForce_r; vec2.sub(r,worldPoint,this.position); // Add linear force vec2.add(this.force,this.force,force); // Compute produced rotational force var rotForce = vec2.crossLength(r,force); // Add rotational force this.angularForce += rotForce; }; /** * Transform a world point to local body frame. * @method toLocalFrame * @param {Array} out The vector to store the result in * @param {Array} worldPoint The input world vector */ Body.prototype.toLocalFrame = function(out, worldPoint){ vec2.toLocalFrame(out, worldPoint, this.position, this.angle); }; /** * Transform a local point to world frame. * @method toWorldFrame * @param {Array} out The vector to store the result in * @param {Array} localPoint The input local vector */ Body.prototype.toWorldFrame = function(out, localPoint){ vec2.toGlobalFrame(out, localPoint, this.position, this.angle); }; /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. * @method fromPolygon * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. * @param {Object} [options] * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @return {Boolean} True on success, else false. */ Body.prototype.fromPolygon = function(path,options){ options = options || {}; // Remove all shapes for(var i=this.shapes.length; i>=0; --i){ this.removeShape(this.shapes[i]); } var p = new decomp.Polygon(); p.vertices = path; // Make it counter-clockwise p.makeCCW(); if(typeof(options.removeCollinearPoints) === "number"){ p.removeCollinearPoints(options.removeCollinearPoints); } // Check if any line segment intersects the path itself if(typeof(options.skipSimpleCheck) === "undefined"){ if(!p.isSimple()){ return false; } } // Save this path for later this.concavePath = p.vertices.slice(0); for(var i=0; i<this.concavePath.length; i++){ var v = [0,0]; vec2.copy(v,this.concavePath[i]); this.concavePath[i] = v; } // Slow or fast decomp? var convexes; if(options.optimalDecomp){ convexes = p.decomp(); } else { convexes = p.quickDecomp(); } var cm = vec2.create(); // Add convexes for(var i=0; i!==convexes.length; i++){ // Create convex var c = new Convex(convexes[i].vertices); // Move all vertices so its center of mass is in the local center of the convex for(var j=0; j!==c.vertices.length; j++){ var v = c.vertices[j]; vec2.sub(v,v,c.centerOfMass); } vec2.scale(cm,c.centerOfMass,1); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); // Add the shape this.addShape(c,cm); } this.adjustCenterOfMass(); this.aabbNeedsUpdate = true; return true; }; var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0), adjustCenterOfMass_tmp2 = vec2.fromValues(0,0), adjustCenterOfMass_tmp3 = vec2.fromValues(0,0), adjustCenterOfMass_tmp4 = vec2.fromValues(0,0); /** * Moves the shape offsets so their center of mass becomes the body center of mass. * @method adjustCenterOfMass */ Body.prototype.adjustCenterOfMass = function(){ var offset_times_area = adjustCenterOfMass_tmp2, sum = adjustCenterOfMass_tmp3, cm = adjustCenterOfMass_tmp4, totalArea = 0; vec2.set(sum,0,0); for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; vec2.scale(offset_times_area,offset,s.area); vec2.add(sum,sum,offset_times_area); totalArea += s.area; } vec2.scale(cm,sum,1/totalArea); // Now move all shapes for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; // Offset may be undefined. Fix that. if(!offset){ offset = this.shapeOffsets[i] = vec2.create(); } vec2.sub(offset,offset,cm); } // Move the body position too vec2.add(this.position,this.position,cm); // And concave path for(var i=0; this.concavePath && i<this.concavePath.length; i++){ vec2.sub(this.concavePath[i], this.concavePath[i], cm); } this.updateMassProperties(); this.updateBoundingRadius(); }; /** * Sets the force on the body to zero. * @method setZeroForce */ Body.prototype.setZeroForce = function(){ vec2.set(this.force,0.0,0.0); this.angularForce = 0.0; }; Body.prototype.resetConstraintVelocity = function(){ var b = this, vlambda = b.vlambda; vec2.set(vlambda,0,0); b.wlambda = 0; }; Body.prototype.addConstraintVelocity = function(){ var b = this, v = b.velocity; vec2.add( v, v, b.vlambda); b.angularVelocity += b.wlambda; }; /** * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details. * @method applyDamping * @param {number} dt Current time step */ Body.prototype.applyDamping = function(dt){ if(this.type === Body.DYNAMIC){ // Only for dynamic bodies var v = this.velocity; vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); } }; /** * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. * @method wakeUp */ Body.prototype.wakeUp = function(){ var s = this.sleepState; this.sleepState = Body.AWAKE; this.idleTime = 0; if(s !== Body.AWAKE){ this.emit(Body.wakeUpEvent); } }; /** * Force body sleep * @method sleep */ Body.prototype.sleep = function(){ this.sleepState = Body.SLEEPING; this.angularVelocity = 0; this.angularForce = 0; vec2.set(this.velocity,0,0); vec2.set(this.force,0,0); this.emit(Body.sleepEvent); }; /** * Called every timestep to update internal sleep timer and change sleep state if needed. * @method sleepTick * @param {number} time The world time in seconds * @param {boolean} dontSleep * @param {number} dt */ Body.prototype.sleepTick = function(time, dontSleep, dt){ if(!this.allowSleep || this.type === Body.SLEEPING){ return; } this.wantsToSleep = false; var sleepState = this.sleepState, speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); // Add to idle time if(speedSquared >= speedLimitSquared){ this.idleTime = 0; this.sleepState = Body.AWAKE; } else { this.idleTime += dt; this.sleepState = Body.SLEEPY; } if(this.idleTime > this.sleepTimeLimit){ if(!dontSleep){ this.sleep(); } else { this.wantsToSleep = true; } } /* if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){ this.sleepState = Body.SLEEPY; // Sleepy this.timeLastSleepy = time; this.emit(Body.sleepyEvent); } else if(sleepState===Body.SLEEPY && speedSquared >= speedLimitSquared){ this.wakeUp(); // Wake up } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){ this.wantsToSleep = true; if(!dontSleep){ this.sleep(); } } */ }; Body.prototype.getVelocityFromPosition = function(store, timeStep){ store = store || vec2.create(); vec2.sub(store, this.position, this.previousPosition); vec2.scale(store, store, 1/timeStep); return store; }; Body.prototype.getAngularVelocityFromPosition = function(timeStep){ return (this.angle - this.previousAngle) / timeStep; }; /** * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. * @method overlaps * @param {Body} body * @return {boolean} */ Body.prototype.overlaps = function(body){ return this.world.overlapKeeper.bodiesAreOverlapping(this, body); }; /** * @event sleepy */ Body.sleepyEvent = { type: "sleepy" }; /** * @event sleep */ Body.sleepEvent = { type: "sleep" }; /** * @event wakeup */ Body.wakeUpEvent = { type: "wakeup" }; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Body.KINEMATIC = 4; /** * @property AWAKE * @type {Number} * @static */ Body.AWAKE = 0; /** * @property SLEEPY * @type {Number} * @static */ Body.SLEEPY = 1; /** * @property SLEEPING * @type {Number} * @static */ Body.SLEEPING = 2; },{"../collision/AABB":9,"../events/EventEmitter":27,"../math/vec2":31,"../shapes/Convex":39,"__browserify_Buffer":1,"__browserify_process":2,"poly-decomp":7}],33:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/objects\\LinearSpring.js",__dirname="/objects";var vec2 = require('../math/vec2'); var Spring = require('./Spring'); var Utils = require('../utils/Utils'); module.exports = LinearSpring; /** * A spring, connecting two bodies. * * The Spring explicitly adds force and angularForce to the bodies. * * @class LinearSpring * @extends Spring * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. * @param {number} [options.damping=1] A number >= 0. Default: 1 * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. * @param {Array} [options.worldAnchorB] * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. * @param {Array} [options.localAnchorB] */ function LinearSpring(bodyA,bodyB,options){ options = options || {}; Spring.call(this, bodyA, bodyB, options); /** * Anchor for bodyA in local bodyA coordinates. * @property localAnchorA * @type {Array} */ this.localAnchorA = vec2.fromValues(0,0); /** * Anchor for bodyB in local bodyB coordinates. * @property localAnchorB * @type {Array} */ this.localAnchorB = vec2.fromValues(0,0); if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } var worldAnchorA = vec2.create(); var worldAnchorB = vec2.create(); this.getWorldAnchorA(worldAnchorA); this.getWorldAnchorB(worldAnchorB); var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); /** * Rest length of the spring. * @property restLength * @type {number} */ this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; } LinearSpring.prototype = new Spring(); /** * Set the anchor point on body A, using world coordinates. * @method setWorldAnchorA * @param {Array} worldAnchorA */ LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); }; /** * Set the anchor point on body B, using world coordinates. * @method setWorldAnchorB * @param {Array} worldAnchorB */ LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); }; /** * Get the anchor point on body A, in world coordinates. * @method getWorldAnchorA * @param {Array} result The vector to store the result in. */ LinearSpring.prototype.getWorldAnchorA = function(result){ this.bodyA.toWorldFrame(result, this.localAnchorA); }; /** * Get the anchor point on body B, in world coordinates. * @method getWorldAnchorB * @param {Array} result The vector to store the result in. */ LinearSpring.prototype.getWorldAnchorB = function(result){ this.bodyB.toWorldFrame(result, this.localAnchorB); }; var applyForce_r = vec2.create(), applyForce_r_unit = vec2.create(), applyForce_u = vec2.create(), applyForce_f = vec2.create(), applyForce_worldAnchorA = vec2.create(), applyForce_worldAnchorB = vec2.create(), applyForce_ri = vec2.create(), applyForce_rj = vec2.create(), applyForce_tmp = vec2.create(); /** * Apply the spring force to the connected bodies. * @method applyForce */ LinearSpring.prototype.applyForce = function(){ var k = this.stiffness, d = this.damping, l = this.restLength, bodyA = this.bodyA, bodyB = this.bodyB, r = applyForce_r, r_unit = applyForce_r_unit, u = applyForce_u, f = applyForce_f, tmp = applyForce_tmp; var worldAnchorA = applyForce_worldAnchorA, worldAnchorB = applyForce_worldAnchorB, ri = applyForce_ri, rj = applyForce_rj; // Get world anchors this.getWorldAnchorA(worldAnchorA); this.getWorldAnchorB(worldAnchorB); // Get offset points vec2.sub(ri, worldAnchorA, bodyA.position); vec2.sub(rj, worldAnchorB, bodyB.position); // Compute distance vector between world anchor points vec2.sub(r, worldAnchorB, worldAnchorA); var rlen = vec2.len(r); vec2.normalize(r_unit,r); //console.log(rlen) //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) // Compute relative velocity of the anchor points, u vec2.sub(u, bodyB.velocity, bodyA.velocity); vec2.crossZV(tmp, bodyB.angularVelocity, rj); vec2.add(u, u, tmp); vec2.crossZV(tmp, bodyA.angularVelocity, ri); vec2.sub(u, u, tmp); // F = - k * ( x - L ) - D * ( u ) vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); // Add forces to bodies vec2.sub( bodyA.force, bodyA.force, f); vec2.add( bodyB.force, bodyB.force, f); // Angular force var ri_x_f = vec2.crossLength(ri, f); var rj_x_f = vec2.crossLength(rj, f); bodyA.angularForce -= ri_x_f; bodyB.angularForce += rj_x_f; }; },{"../math/vec2":31,"../utils/Utils":50,"./Spring":35,"__browserify_Buffer":1,"__browserify_process":2}],34:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/objects\\RotationalSpring.js",__dirname="/objects";var vec2 = require('../math/vec2'); var Spring = require('./Spring'); module.exports = RotationalSpring; /** * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. * * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. * * @class RotationalSpring * @extends Spring * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. * @param {number} [options.damping=1] A number >= 0. */ function RotationalSpring(bodyA, bodyB, options){ options = options || {}; Spring.call(this, bodyA, bodyB, options); /** * Rest angle of the spring. * @property restAngle * @type {number} */ this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; } RotationalSpring.prototype = new Spring(); /** * Apply the spring force to the connected bodies. * @method applyForce */ RotationalSpring.prototype.applyForce = function(){ var k = this.stiffness, d = this.damping, l = this.restAngle, bodyA = this.bodyA, bodyB = this.bodyB, x = bodyB.angle - bodyA.angle, u = bodyB.angularVelocity - bodyA.angularVelocity; var torque = - k * (x - l) - d * u * 0; bodyA.angularForce -= torque; bodyB.angularForce += torque; }; },{"../math/vec2":31,"./Spring":35,"__browserify_Buffer":1,"__browserify_process":2}],35:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/objects\\Spring.js",__dirname="/objects";var vec2 = require('../math/vec2'); var Utils = require('../utils/Utils'); module.exports = Spring; /** * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. * * @class Spring * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. * @param {number} [options.damping=1] A number >= 0. Default: 1 * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. * @param {Array} [options.localAnchorB] * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. * @param {Array} [options.worldAnchorB] */ function Spring(bodyA, bodyB, options){ options = Utils.defaults(options,{ stiffness: 100, damping: 1, }); /** * Stiffness of the spring. * @property stiffness * @type {number} */ this.stiffness = options.stiffness; /** * Damping of the spring. * @property damping * @type {number} */ this.damping = options.damping; /** * First connected body. * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second connected body. * @property bodyB * @type {Body} */ this.bodyB = bodyB; } /** * Apply the spring force to the connected bodies. * @method applyForce */ Spring.prototype.applyForce = function(){ // To be implemented by subclasses }; },{"../math/vec2":31,"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],36:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/p2.js",__dirname="/";// Export p2 classes module.exports = { AABB : require('./collision/AABB'), AngleLockEquation : require('./equations/AngleLockEquation'), Body : require('./objects/Body'), Broadphase : require('./collision/Broadphase'), Capsule : require('./shapes/Capsule'), Circle : require('./shapes/Circle'), Constraint : require('./constraints/Constraint'), ContactEquation : require('./equations/ContactEquation'), ContactMaterial : require('./material/ContactMaterial'), Convex : require('./shapes/Convex'), DistanceConstraint : require('./constraints/DistanceConstraint'), Equation : require('./equations/Equation'), EventEmitter : require('./events/EventEmitter'), FrictionEquation : require('./equations/FrictionEquation'), GearConstraint : require('./constraints/GearConstraint'), GridBroadphase : require('./collision/GridBroadphase'), GSSolver : require('./solver/GSSolver'), Heightfield : require('./shapes/Heightfield'), Line : require('./shapes/Line'), LockConstraint : require('./constraints/LockConstraint'), Material : require('./material/Material'), Narrowphase : require('./collision/Narrowphase'), NaiveBroadphase : require('./collision/NaiveBroadphase'), Particle : require('./shapes/Particle'), Plane : require('./shapes/Plane'), RevoluteConstraint : require('./constraints/RevoluteConstraint'), PrismaticConstraint : require('./constraints/PrismaticConstraint'), Rectangle : require('./shapes/Rectangle'), RotationalVelocityEquation : require('./equations/RotationalVelocityEquation'), SAPBroadphase : require('./collision/SAPBroadphase'), Shape : require('./shapes/Shape'), Solver : require('./solver/Solver'), Spring : require('./objects/Spring'), LinearSpring : require('./objects/LinearSpring'), RotationalSpring : require('./objects/RotationalSpring'), Utils : require('./utils/Utils'), World : require('./world/World'), vec2 : require('./math/vec2'), version : require('../package.json').version, }; },{"../package.json":8,"./collision/AABB":9,"./collision/Broadphase":10,"./collision/GridBroadphase":11,"./collision/NaiveBroadphase":12,"./collision/Narrowphase":13,"./collision/SAPBroadphase":14,"./constraints/Constraint":15,"./constraints/DistanceConstraint":16,"./constraints/GearConstraint":17,"./constraints/LockConstraint":18,"./constraints/PrismaticConstraint":19,"./constraints/RevoluteConstraint":20,"./equations/AngleLockEquation":21,"./equations/ContactEquation":22,"./equations/Equation":23,"./equations/FrictionEquation":24,"./equations/RotationalVelocityEquation":26,"./events/EventEmitter":27,"./material/ContactMaterial":28,"./material/Material":29,"./math/vec2":31,"./objects/Body":32,"./objects/LinearSpring":33,"./objects/RotationalSpring":34,"./objects/Spring":35,"./shapes/Capsule":37,"./shapes/Circle":38,"./shapes/Convex":39,"./shapes/Heightfield":40,"./shapes/Line":41,"./shapes/Particle":42,"./shapes/Plane":43,"./shapes/Rectangle":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/Utils":50,"./world/World":54,"__browserify_Buffer":1,"__browserify_process":2}],37:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Capsule.js",__dirname="/shapes";var Shape = require('./Shape') , vec2 = require('../math/vec2'); module.exports = Capsule; /** * Capsule shape class. * @class Capsule * @constructor * @extends Shape * @param {Number} [length=1] The distance between the end points * @param {Number} [radius=1] Radius of the capsule * @example * var radius = 1; * var length = 2; * var capsuleShape = new Capsule(length, radius); * body.addShape(capsuleShape); */ function Capsule(length, radius){ /** * The distance between the end points. * @property {Number} length */ this.length = length || 1; /** * The radius of the capsule. * @property {Number} radius */ this.radius = radius || 1; Shape.call(this,Shape.CAPSULE); } Capsule.prototype = new Shape(); /** * Compute the mass moment of inertia of the Capsule. * @method conputeMomentOfInertia * @param {Number} mass * @return {Number} * @todo */ Capsule.prototype.computeMomentOfInertia = function(mass){ // Approximate with rectangle var r = this.radius, w = this.length + r, // 2*r is too much, 0 is too little h = r*2; return mass * (h*h + w*w) / 12; }; /** * @method updateBoundingRadius */ Capsule.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.radius + this.length/2; }; /** * @method updateArea */ Capsule.prototype.updateArea = function(){ this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; }; var r = vec2.create(); /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Capsule.prototype.computeAABB = function(out, position, angle){ var radius = this.radius; // Compute center position of one of the the circles, world oriented, but with local offset vec2.set(r,this.length / 2,0); if(angle !== 0){ vec2.rotate(r,r,angle); } // Get bounds vec2.set(out.upperBound, Math.max(r[0]+radius, -r[0]+radius), Math.max(r[1]+radius, -r[1]+radius)); vec2.set(out.lowerBound, Math.min(r[0]-radius, -r[0]-radius), Math.min(r[1]-radius, -r[1]-radius)); // Add offset vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); }; },{"../math/vec2":31,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],38:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Circle.js",__dirname="/shapes";var Shape = require('./Shape') , vec2 = require('../math/vec2'); module.exports = Circle; /** * Circle shape class. * @class Circle * @extends Shape * @constructor * @param {number} [radius=1] The radius of this circle * * @example * var radius = 1; * var circleShape = new Circle(radius); * body.addShape(circleShape); */ function Circle(radius){ /** * The radius of the circle. * @property radius * @type {number} */ this.radius = radius || 1; Shape.call(this,Shape.CIRCLE); } Circle.prototype = new Shape(); /** * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Circle.prototype.computeMomentOfInertia = function(mass){ var r = this.radius; return mass * r * r / 2; }; /** * @method updateBoundingRadius * @return {Number} */ Circle.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.radius; }; /** * @method updateArea * @return {Number} */ Circle.prototype.updateArea = function(){ this.area = Math.PI * this.radius * this.radius; }; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Circle.prototype.computeAABB = function(out, position, angle){ var r = this.radius; vec2.set(out.upperBound, r, r); vec2.set(out.lowerBound, -r, -r); if(position){ vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); } }; },{"../math/vec2":31,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],39:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Convex.js",__dirname="/shapes";var Shape = require('./Shape') , vec2 = require('../math/vec2') , polyk = require('../math/polyk') , decomp = require('poly-decomp'); module.exports = Convex; /** * Convex shape class. * @class Convex * @constructor * @extends Shape * @param {Array} vertices An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. * @param {Array} [axes] An array of unit length vectors, representing the symmetry axes in the convex. * @example * // Create a box * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; * var convexShape = new Convex(vertices); * body.addShape(convexShape); */ function Convex(vertices, axes){ /** * Vertices defined in the local frame. * @property vertices * @type {Array} */ this.vertices = []; /** * Axes defined in the local frame. * @property axes * @type {Array} */ this.axes = []; // Copy the verts for(var i=0; i<vertices.length; i++){ var v = vec2.create(); vec2.copy(v,vertices[i]); this.vertices.push(v); } if(axes){ // Copy the axes for(var i=0; i < axes.length; i++){ var axis = vec2.create(); vec2.copy(axis, axes[i]); this.axes.push(axis); } } else { // Construct axes from the vertex data for(var i = 0; i < vertices.length; i++){ // Get the world edge var worldPoint0 = vertices[i]; var worldPoint1 = vertices[(i+1) % vertices.length]; var normal = vec2.create(); vec2.sub(normal, worldPoint1, worldPoint0); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, normal); vec2.normalize(normal, normal); this.axes.push(normal); } } /** * The center of mass of the Convex * @property centerOfMass * @type {Array} */ this.centerOfMass = vec2.fromValues(0,0); /** * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. * @property triangles * @type {Array} */ this.triangles = []; if(this.vertices.length){ this.updateTriangles(); this.updateCenterOfMass(); } /** * The bounding radius of the convex * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; Shape.call(this, Shape.CONVEX); this.updateBoundingRadius(); this.updateArea(); if(this.area < 0){ throw new Error("Convex vertices must be given in conter-clockwise winding."); } } Convex.prototype = new Shape(); var tmpVec1 = vec2.create(); var tmpVec2 = vec2.create(); /** * Project a Convex onto a world-oriented axis * @method projectOntoAxis * @static * @param {Array} offset * @param {Array} localAxis * @param {Array} result */ Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ var max=null, min=null, v, value, localAxis = tmpVec1; // Get projected position of all vertices for(var i=0; i<this.vertices.length; i++){ v = this.vertices[i]; value = vec2.dot(v, localAxis); if(max === null || value > max){ max = value; } if(min === null || value < min){ min = value; } } if(min > max){ var t = min; min = max; max = t; } vec2.set(result, min, max); }; Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ var worldAxis = tmpVec2; this.projectOntoLocalAxis(localAxis, result); // Project the position of the body onto the axis - need to add this to the result if(shapeAngle !== 0){ vec2.rotate(worldAxis, localAxis, shapeAngle); } else { worldAxis = localAxis; } var offset = vec2.dot(shapeOffset, worldAxis); vec2.set(result, result[0] + offset, result[1] + offset); }; /** * Update the .triangles property * @method updateTriangles */ Convex.prototype.updateTriangles = function(){ this.triangles.length = 0; // Rewrite on polyk notation, array of numbers var polykVerts = []; for(var i=0; i<this.vertices.length; i++){ var v = this.vertices[i]; polykVerts.push(v[0],v[1]); } // Triangulate var triangles = polyk.Triangulate(polykVerts); // Loop over all triangles, add their inertia contributions to I for(var i=0; i<triangles.length; i+=3){ var id1 = triangles[i], id2 = triangles[i+1], id3 = triangles[i+2]; // Add to triangles this.triangles.push([id1,id2,id3]); } }; var updateCenterOfMass_centroid = vec2.create(), updateCenterOfMass_centroid_times_mass = vec2.create(), updateCenterOfMass_a = vec2.create(), updateCenterOfMass_b = vec2.create(), updateCenterOfMass_c = vec2.create(), updateCenterOfMass_ac = vec2.create(), updateCenterOfMass_ca = vec2.create(), updateCenterOfMass_cb = vec2.create(), updateCenterOfMass_n = vec2.create(); /** * Update the .centerOfMass property. * @method updateCenterOfMass */ Convex.prototype.updateCenterOfMass = function(){ var triangles = this.triangles, verts = this.vertices, cm = this.centerOfMass, centroid = updateCenterOfMass_centroid, n = updateCenterOfMass_n, a = updateCenterOfMass_a, b = updateCenterOfMass_b, c = updateCenterOfMass_c, ac = updateCenterOfMass_ac, ca = updateCenterOfMass_ca, cb = updateCenterOfMass_cb, centroid_times_mass = updateCenterOfMass_centroid_times_mass; vec2.set(cm,0,0); var totalArea = 0; for(var i=0; i!==triangles.length; i++){ var t = triangles[i], a = verts[t[0]], b = verts[t[1]], c = verts[t[2]]; vec2.centroid(centroid,a,b,c); // Get mass for the triangle (density=1 in this case) // http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors var m = Convex.triangleArea(a,b,c); totalArea += m; // Add to center of mass vec2.scale(centroid_times_mass, centroid, m); vec2.add(cm, cm, centroid_times_mass); } vec2.scale(cm,cm,1/totalArea); }; /** * Compute the mass moment of inertia of the Convex. * @method computeMomentOfInertia * @param {Number} mass * @return {Number} * @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/ */ Convex.prototype.computeMomentOfInertia = function(mass){ var denom = 0.0, numer = 0.0, N = this.vertices.length; for(var j = N-1, i = 0; i < N; j = i, i ++){ var p0 = this.vertices[j]; var p1 = this.vertices[i]; var a = Math.abs(vec2.crossLength(p0,p1)); var b = vec2.dot(p1,p1) + vec2.dot(p1,p0) + vec2.dot(p0,p0); denom += a * b; numer += a; } return (mass / 6.0) * (denom / numer); }; /** * Updates the .boundingRadius property * @method updateBoundingRadius */ Convex.prototype.updateBoundingRadius = function(){ var verts = this.vertices, r2 = 0; for(var i=0; i!==verts.length; i++){ var l2 = vec2.squaredLength(verts[i]); if(l2 > r2){ r2 = l2; } } this.boundingRadius = Math.sqrt(r2); }; /** * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. * @static * @method triangleArea * @param {Array} a * @param {Array} b * @param {Array} c * @return {Number} */ Convex.triangleArea = function(a,b,c){ return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; }; /** * Update the .area * @method updateArea */ Convex.prototype.updateArea = function(){ this.updateTriangles(); this.area = 0; var triangles = this.triangles, verts = this.vertices; for(var i=0; i!==triangles.length; i++){ var t = triangles[i], a = verts[t[0]], b = verts[t[1]], c = verts[t[2]]; // Get mass for the triangle (density=1 in this case) var m = Convex.triangleArea(a,b,c); this.area += m; } }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Convex.prototype.computeAABB = function(out, position, angle){ out.setFromPoints(this.vertices, position, angle, 0); }; },{"../math/polyk":30,"../math/vec2":31,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2,"poly-decomp":7}],40:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Heightfield.js",__dirname="/shapes";var Shape = require('./Shape') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = Heightfield; /** * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". * @class Heightfield * @extends Shape * @constructor * @param {Array} data An array of Y values that will be used to construct the terrain. * @param {object} options * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. * @param {Number} [options.maxValue] Maximum value. * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. * @todo Should be possible to use along all axes, not just y * * @example * // Generate some height data (y-values). * var data = []; * for(var i = 0; i < 1000; i++){ * var y = 0.5 * Math.cos(0.2 * i); * data.push(y); * } * * // Create the heightfield shape * var heightfieldShape = new Heightfield(data, { * elementWidth: 1 // Distance between the data points in X direction * }); * var heightfieldBody = new Body(); * heightfieldBody.addShape(heightfieldShape); * world.addBody(heightfieldBody); */ function Heightfield(data, options){ options = Utils.defaults(options, { maxValue : null, minValue : null, elementWidth : 0.1 }); if(options.minValue === null || options.maxValue === null){ options.maxValue = data[0]; options.minValue = data[0]; for(var i=0; i !== data.length; i++){ var v = data[i]; if(v > options.maxValue){ options.maxValue = v; } if(v < options.minValue){ options.minValue = v; } } } /** * An array of numbers, or height values, that are spread out along the x axis. * @property {array} data */ this.data = data; /** * Max value of the data * @property {number} maxValue */ this.maxValue = options.maxValue; /** * Max value of the data * @property {number} minValue */ this.minValue = options.minValue; /** * The width of each element * @property {number} elementWidth */ this.elementWidth = options.elementWidth; Shape.call(this,Shape.HEIGHTFIELD); } Heightfield.prototype = new Shape(); /** * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Heightfield.prototype.computeMomentOfInertia = function(mass){ return Number.MAX_VALUE; }; Heightfield.prototype.updateBoundingRadius = function(){ this.boundingRadius = Number.MAX_VALUE; }; Heightfield.prototype.updateArea = function(){ var data = this.data, area = 0; for(var i=0; i<data.length-1; i++){ area += (data[i]+data[i+1]) / 2 * this.elementWidth; } this.area = area; }; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Heightfield.prototype.computeAABB = function(out, position, angle){ // Use the max data rectangle out.upperBound[0] = this.elementWidth * this.data.length + position[0]; out.upperBound[1] = this.maxValue + position[1]; out.lowerBound[0] = position[0]; out.lowerBound[1] = -Number.MAX_VALUE; // Infinity }; },{"../math/vec2":31,"../utils/Utils":50,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],41:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Line.js",__dirname="/shapes";var Shape = require('./Shape') , vec2 = require('../math/vec2'); module.exports = Line; /** * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * @class Line * @param {Number} [length=1] The total length of the line * @extends Shape * @constructor */ function Line(length){ /** * Length of this line * @property length * @type {Number} */ this.length = length || 1; Shape.call(this,Shape.LINE); } Line.prototype = new Shape(); Line.prototype.computeMomentOfInertia = function(mass){ return mass * Math.pow(this.length,2) / 12; }; Line.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.length/2; }; var points = [vec2.create(),vec2.create()]; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Line.prototype.computeAABB = function(out, position, angle){ var l2 = this.length / 2; vec2.set(points[0], -l2, 0); vec2.set(points[1], l2, 0); out.setFromPoints(points,position,angle,0); }; },{"../math/vec2":31,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],42:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Particle.js",__dirname="/shapes";var Shape = require('./Shape') , vec2 = require('../math/vec2'); module.exports = Particle; /** * Particle shape class. * @class Particle * @constructor * @extends Shape */ function Particle(){ Shape.call(this,Shape.PARTICLE); } Particle.prototype = new Shape(); Particle.prototype.computeMomentOfInertia = function(mass){ return 0; // Can't rotate a particle }; Particle.prototype.updateBoundingRadius = function(){ this.boundingRadius = 0; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Particle.prototype.computeAABB = function(out, position, angle){ vec2.copy(out.lowerBound, position); vec2.copy(out.upperBound, position); }; },{"../math/vec2":31,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],43:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Plane.js",__dirname="/shapes";var Shape = require('./Shape') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = Plane; /** * Plane shape class. The plane is facing in the Y direction. * @class Plane * @extends Shape * @constructor */ function Plane(){ Shape.call(this,Shape.PLANE); } Plane.prototype = new Shape(); /** * Compute moment of inertia * @method computeMomentOfInertia */ Plane.prototype.computeMomentOfInertia = function(mass){ return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here }; /** * Update the bounding radius * @method updateBoundingRadius */ Plane.prototype.updateBoundingRadius = function(){ this.boundingRadius = Number.MAX_VALUE; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Plane.prototype.computeAABB = function(out, position, angle){ var a = 0, set = vec2.set; if(typeof(angle) === "number"){ a = angle % (2*Math.PI); } if(a === 0){ // y goes from -inf to 0 set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, 0); } else if(a === Math.PI / 2){ // x goes from 0 to inf set(out.lowerBound, 0, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } else if(a === Math.PI){ // y goes from 0 to inf set(out.lowerBound, -Number.MAX_VALUE, 0); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } else if(a === 3*Math.PI/2){ // x goes from -inf to 0 set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, 0, Number.MAX_VALUE); } else { // Set max bounds set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); }; Plane.prototype.updateArea = function(){ this.area = Number.MAX_VALUE; }; },{"../math/vec2":31,"../utils/Utils":50,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],44:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Rectangle.js",__dirname="/shapes";var vec2 = require('../math/vec2') , Shape = require('./Shape') , Convex = require('./Convex'); module.exports = Rectangle; /** * Rectangle shape class. * @class Rectangle * @constructor * @param {Number} [width=1] Width * @param {Number} [height=1] Height * @extends Convex */ function Rectangle(width, height){ /** * Total width of the rectangle * @property width * @type {Number} */ this.width = width || 1; /** * Total height of the rectangle * @property height * @type {Number} */ this.height = height || 1; var verts = [ vec2.fromValues(-width/2, -height/2), vec2.fromValues( width/2, -height/2), vec2.fromValues( width/2, height/2), vec2.fromValues(-width/2, height/2)]; var axes = [vec2.fromValues(1, 0), vec2.fromValues(0, 1)]; Convex.call(this, verts, axes); this.type = Shape.RECTANGLE; } Rectangle.prototype = new Convex([]); /** * Compute moment of inertia * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Rectangle.prototype.computeMomentOfInertia = function(mass){ var w = this.width, h = this.height; return mass * (h*h + w*w) / 12; }; /** * Update the bounding radius * @method updateBoundingRadius */ Rectangle.prototype.updateBoundingRadius = function(){ var w = this.width, h = this.height; this.boundingRadius = Math.sqrt(w*w + h*h) / 2; }; var corner1 = vec2.create(), corner2 = vec2.create(), corner3 = vec2.create(), corner4 = vec2.create(); /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Rectangle.prototype.computeAABB = function(out, position, angle){ out.setFromPoints(this.vertices,position,angle,0); }; Rectangle.prototype.updateArea = function(){ this.area = this.width * this.height; }; },{"../math/vec2":31,"./Convex":39,"./Shape":45,"__browserify_Buffer":1,"__browserify_process":2}],45:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/shapes\\Shape.js",__dirname="/shapes";module.exports = Shape; /** * Base class for shapes. * @class Shape * @constructor * @param {Number} type */ function Shape(type){ /** * The type of the shape. One of: * * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} * * {{#crossLink "Shape/RECTANGLE:property"}}Shape.RECTANGLE{{/crossLink}} * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} * * @property {number} type */ this.type = type; /** * Shape object identifier. * @type {Number} * @property id */ this.id = Shape.idCounter++; /** * Bounding circle radius of this shape * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>. * @property collisionGroup * @type {Number} * @example * // Setup bits for each available group * var PLAYER = Math.pow(2,0), * ENEMY = Math.pow(2,1), * GROUND = Math.pow(2,2) * * // Put shapes into their groups * player1Shape.collisionGroup = PLAYER; * player2Shape.collisionGroup = PLAYER; * enemyShape .collisionGroup = ENEMY; * groundShape .collisionGroup = GROUND; * * // Assign groups that each shape collide with. * // Note that the players can collide with ground and enemies, but not with other players. * player1Shape.collisionMask = ENEMY | GROUND; * player2Shape.collisionMask = ENEMY | GROUND; * enemyShape .collisionMask = PLAYER | GROUND; * groundShape .collisionMask = PLAYER | ENEMY; * * @example * // How collision check is done * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ * // The shapes will collide * } */ this.collisionGroup = 1; /** * Collision mask of this shape. See .collisionGroup. * @property collisionMask * @type {Number} */ this.collisionMask = 1; if(type){ this.updateBoundingRadius(); } /** * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. * @property material * @type {Material} */ this.material = null; /** * Area of this shape. * @property area * @type {Number} */ this.area = 0; /** * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. * @property {Boolean} sensor */ this.sensor = false; this.updateArea(); } Shape.idCounter = 0; /** * @static * @property {Number} CIRCLE */ Shape.CIRCLE = 1; /** * @static * @property {Number} PARTICLE */ Shape.PARTICLE = 2; /** * @static * @property {Number} PLANE */ Shape.PLANE = 4; /** * @static * @property {Number} CONVEX */ Shape.CONVEX = 8; /** * @static * @property {Number} LINE */ Shape.LINE = 16; /** * @static * @property {Number} RECTANGLE */ Shape.RECTANGLE = 32; /** * @static * @property {Number} CAPSULE */ Shape.CAPSULE = 64; /** * @static * @property {Number} HEIGHTFIELD */ Shape.HEIGHTFIELD = 128; /** * Should return the moment of inertia around the Z axis of the body given the total mass. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>. * @method computeMomentOfInertia * @param {Number} mass * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. */ Shape.prototype.computeMomentOfInertia = function(mass){ throw new Error("Shape.computeMomentOfInertia is not implemented in this Shape..."); }; /** * Returns the bounding circle radius of this shape. * @method updateBoundingRadius * @return {Number} */ Shape.prototype.updateBoundingRadius = function(){ throw new Error("Shape.updateBoundingRadius is not implemented in this Shape..."); }; /** * Update the .area property of the shape. * @method updateArea */ Shape.prototype.updateArea = function(){ // To be implemented in all subclasses }; /** * Compute the world axis-aligned bounding box (AABB) of this shape. * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Shape.prototype.computeAABB = function(out, position, angle){ // To be implemented in each subclass }; },{"__browserify_Buffer":1,"__browserify_process":2}],46:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/solver\\GSSolver.js",__dirname="/solver";var vec2 = require('../math/vec2') , Solver = require('./Solver') , Utils = require('../utils/Utils') , FrictionEquation = require('../equations/FrictionEquation'); module.exports = GSSolver; /** * Iterative Gauss-Seidel constraint equation solver. * * @class GSSolver * @constructor * @extends Solver * @param {Object} [options] * @param {Number} [options.iterations=10] * @param {Number} [options.tolerance=0] */ function GSSolver(options){ Solver.call(this,options,Solver.GS); options = options || {}; /** * The number of iterations to do when solving. More gives better results, but is more expensive. * @property iterations * @type {Number} */ this.iterations = options.iterations || 10; /** * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. * @property tolerance * @type {Number} */ this.tolerance = options.tolerance || 1e-10; this.arrayStep = 30; this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); /** * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. * @property useZeroRHS * @type {Boolean} */ this.useZeroRHS = false; /** * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example. * The solver will use less iterations if the solution is below the .tolerance. * @property frictionIterations * @type {Number} */ this.frictionIterations = 0; /** * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. * @property {Number} usedIterations */ this.usedIterations = 0; } GSSolver.prototype = new Solver(); function setArrayZero(array){ var l = array.length; while(l--){ array[l] = +0.0; } } /** * Solve the system of equations * @method solve * @param {Number} h Time step * @param {World} world World to solve */ GSSolver.prototype.solve = function(h, world){ this.sortEquations(); var iter = 0, maxIter = this.iterations, maxFrictionIter = this.frictionIterations, equations = this.equations, Neq = equations.length, tolSquared = Math.pow(this.tolerance*Neq, 2), bodies = world.bodies, Nbodies = world.bodies.length, add = vec2.add, set = vec2.set, useZeroRHS = this.useZeroRHS, lambda = this.lambda; this.usedIterations = 0; if(Neq){ for(var i=0; i!==Nbodies; i++){ var b = bodies[i]; // Update solve mass b.updateSolveMassProperties(); } } // Things that does not change during iteration can be computed once if(lambda.length < Neq){ lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); } setArrayZero(lambda); var invCs = this.invCs, Bs = this.Bs, lambda = this.lambda; for(var i=0; i!==equations.length; i++){ var c = equations[i]; if(c.timeStep !== h || c.needsUpdate){ c.timeStep = h; c.update(); } Bs[i] = c.computeB(c.a,c.b,h); invCs[i] = c.computeInvC(c.epsilon); } var q, B, c, deltalambdaTot,i,j; if(Neq !== 0){ for(i=0; i!==Nbodies; i++){ var b = bodies[i]; // Reset vlambda b.resetConstraintVelocity(); } if(maxFrictionIter){ // Iterate over contact equations to get normal forces for(iter=0; iter!==maxFrictionIter; iter++){ // Accumulate the total error for each iteration. deltalambdaTot = 0.0; for(j=0; j!==Neq; j++){ c = equations[j]; var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); deltalambdaTot += Math.abs(deltalambda); } this.usedIterations++; // If the total error is small enough - stop iterate if(deltalambdaTot*deltalambdaTot <= tolSquared){ break; } } GSSolver.updateMultipliers(equations, lambda, 1/h); // Set computed friction force for(j=0; j!==Neq; j++){ var eq = equations[j]; if(eq instanceof FrictionEquation){ var f = 0.0; for(var k=0; k!==eq.contactEquations.length; k++){ f += eq.contactEquations[k].multiplier; } f *= eq.frictionCoefficient / eq.contactEquations.length; eq.maxForce = f; eq.minForce = -f; } } } // Iterate over all equations for(iter=0; iter!==maxIter; iter++){ // Accumulate the total error for each iteration. deltalambdaTot = 0.0; for(j=0; j!==Neq; j++){ c = equations[j]; var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); deltalambdaTot += Math.abs(deltalambda); } this.usedIterations++; // If the total error is small enough - stop iterate if(deltalambdaTot*deltalambdaTot <= tolSquared){ break; } } // Add result to velocity for(i=0; i!==Nbodies; i++){ bodies[i].addConstraintVelocity(); } GSSolver.updateMultipliers(equations, lambda, 1/h); } }; // Sets the .multiplier property of each equation GSSolver.updateMultipliers = function(equations, lambda, invDt){ // Set the .multiplier property of each equation var l = equations.length; while(l--){ equations[l].multiplier = lambda[l] * invDt; } }; GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ // Compute iteration var B = Bs[j], invC = invCs[j], lambdaj = lambda[j], GWlambda = eq.computeGWlambda(); var maxForce = eq.maxForce, minForce = eq.minForce; if(useZeroRHS){ B = 0; } var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); // Clamp if we are not within the min/max interval var lambdaj_plus_deltalambda = lambdaj + deltalambda; if(lambdaj_plus_deltalambda < minForce*dt){ deltalambda = minForce*dt - lambdaj; } else if(lambdaj_plus_deltalambda > maxForce*dt){ deltalambda = maxForce*dt - lambdaj; } lambda[j] += deltalambda; eq.addToWlambda(deltalambda); return deltalambda; }; },{"../equations/FrictionEquation":24,"../math/vec2":31,"../utils/Utils":50,"./Solver":47,"__browserify_Buffer":1,"__browserify_process":2}],47:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/solver\\Solver.js",__dirname="/solver";var Utils = require('../utils/Utils') , EventEmitter = require('../events/EventEmitter'); module.exports = Solver; /** * Base class for constraint solvers. * @class Solver * @constructor * @extends EventEmitter */ function Solver(options,type){ options = options || {}; EventEmitter.call(this); this.type = type; /** * Current equations in the solver. * * @property equations * @type {Array} */ this.equations = []; /** * Function that is used to sort all equations before each solve. * @property equationSortFunction * @type {function|boolean} */ this.equationSortFunction = options.equationSortFunction || false; } Solver.prototype = new EventEmitter(); /** * Method to be implemented in each subclass * @method solve * @param {Number} dt * @param {World} world */ Solver.prototype.solve = function(dt,world){ throw new Error("Solver.solve should be implemented by subclasses!"); }; var mockWorld = {bodies:[]}; /** * Solves all constraints in an island. * @method solveIsland * @param {Number} dt * @param {Island} island */ Solver.prototype.solveIsland = function(dt,island){ this.removeAllEquations(); if(island.equations.length){ // Add equations to solver this.addEquations(island.equations); mockWorld.bodies.length = 0; island.getBodies(mockWorld.bodies); // Solve if(mockWorld.bodies.length){ this.solve(dt,mockWorld); } } }; /** * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. * @method sortEquations */ Solver.prototype.sortEquations = function(){ if(this.equationSortFunction){ this.equations.sort(this.equationSortFunction); } }; /** * Add an equation to be solved. * * @method addEquation * @param {Equation} eq */ Solver.prototype.addEquation = function(eq){ if(eq.enabled){ this.equations.push(eq); } }; /** * Add equations. Same as .addEquation, but this time the argument is an array of Equations * * @method addEquations * @param {Array} eqs */ Solver.prototype.addEquations = function(eqs){ //Utils.appendArray(this.equations,eqs); for(var i=0, N=eqs.length; i!==N; i++){ var eq = eqs[i]; if(eq.enabled){ this.equations.push(eq); } } }; /** * Remove an equation. * * @method removeEquation * @param {Equation} eq */ Solver.prototype.removeEquation = function(eq){ var i = this.equations.indexOf(eq); if(i !== -1){ this.equations.splice(i,1); } }; /** * Remove all currently added equations. * * @method removeAllEquations */ Solver.prototype.removeAllEquations = function(){ this.equations.length=0; }; Solver.GS = 1; Solver.ISLAND = 2; },{"../events/EventEmitter":27,"../utils/Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],48:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/utils\\OverlapKeeper.js",__dirname="/utils";var TupleDictionary = require('./TupleDictionary'); var Utils = require('./Utils'); module.exports = OverlapKeeper; /** * Keeps track of overlaps in the current state and the last step state. * @class OverlapKeeper * @constructor */ function OverlapKeeper() { this.overlappingShapesLastState = new TupleDictionary(); this.overlappingShapesCurrentState = new TupleDictionary(); this.recordPool = []; this.tmpDict = new TupleDictionary(); this.tmpArray1 = []; } /** * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. * @method tick */ OverlapKeeper.prototype.tick = function() { var last = this.overlappingShapesLastState; var current = this.overlappingShapesCurrentState; // Save old objects into pool var l = last.keys.length; while(l--){ var key = last.keys[l]; var lastObject = last.getByKey(key); var currentObject = current.getByKey(key); if(lastObject && !currentObject){ // The record is only used in the "last" dict, and will be removed. We might as well pool it. this.recordPool.push(lastObject); } } // Clear last object last.reset(); // Transfer from new object to old last.copy(current); // Clear current object current.reset(); }; /** * @method setOverlapping * @param {Body} bodyA * @param {Body} shapeA * @param {Body} bodyB * @param {Body} shapeB */ OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { var last = this.overlappingShapesLastState; var current = this.overlappingShapesCurrentState; // Store current contact state if(!current.get(shapeA.id, shapeB.id)){ var data; if(this.recordPool.length){ data = this.recordPool.pop(); data.set(bodyA, shapeA, bodyB, shapeB); } else { data = new OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB); } current.set(shapeA.id, shapeB.id, data); } }; OverlapKeeper.prototype.getNewOverlaps = function(result){ return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); }; OverlapKeeper.prototype.getEndOverlaps = function(result){ return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); }; /** * Checks if two bodies are currently overlapping. * @method bodiesAreOverlapping * @param {Body} bodyA * @param {Body} bodyB * @return {boolean} */ OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ var current = this.overlappingShapesCurrentState; var l = current.keys.length; while(l--){ var key = current.keys[l]; var data = current.data[key]; if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ return true; } } return false; }; OverlapKeeper.prototype.getDiff = function(dictA, dictB, result){ var result = result || []; var last = dictA; var current = dictB; result.length = 0; var l = current.keys.length; while(l--){ var key = current.keys[l]; var data = current.data[key]; if(!data){ throw new Error('Key '+key+' had no data!'); } var lastData = last.data[key]; if(!lastData){ // Not overlapping in last state, but in current. result.push(data); } } return result; }; OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ var idA = shapeA.id|0, idB = shapeB.id|0; var last = this.overlappingShapesLastState; var current = this.overlappingShapesCurrentState; // Not in last but in new return !!!last.get(idA, idB) && !!current.get(idA, idB); }; OverlapKeeper.prototype.getNewBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getNewOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getEndBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getEndOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getBodyDiff = function(overlaps, result){ result = result || []; var accumulator = this.tmpDict; var l = overlaps.length; while(l--){ var data = overlaps[l]; // Since we use body id's for the accumulator, these will be a subset of the original one accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); } l = accumulator.keys.length; while(l--){ var data = accumulator.getByKey(accumulator.keys[l]); if(data){ result.push(data.bodyA, data.bodyB); } } accumulator.reset(); return result; }; /** * Overlap data container for the OverlapKeeper * @class OverlapKeeperRecord * @constructor * @param {Body} bodyA * @param {Shape} shapeA * @param {Body} bodyB * @param {Shape} shapeB */ function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ /** * @property {Shape} shapeA */ this.shapeA = shapeA; /** * @property {Shape} shapeB */ this.shapeB = shapeB; /** * @property {Body} bodyA */ this.bodyA = bodyA; /** * @property {Body} bodyB */ this.bodyB = bodyB; } /** * Set the data for the record * @method set * @param {Body} bodyA * @param {Shape} shapeA * @param {Body} bodyB * @param {Shape} shapeB */ OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); }; },{"./TupleDictionary":49,"./Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],49:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/utils\\TupleDictionary.js",__dirname="/utils";var Utils = require('./Utils'); module.exports = TupleDictionary; /** * @class TupleDictionary * @constructor */ function TupleDictionary() { /** * The data storage * @property data * @type {Object} */ this.data = {}; /** * Keys that are currently used. * @property {Array} keys */ this.keys = []; } /** * Generate a key given two integers * @method getKey * @param {number} i * @param {number} j * @return {string} */ TupleDictionary.prototype.getKey = function(id1, id2) { id1 = id1|0; id2 = id2|0; if ( (id1|0) === (id2|0) ){ return -1; } // valid for values < 2^16 return ((id1|0) > (id2|0) ? (id1 << 16) | (id2 & 0xFFFF) : (id2 << 16) | (id1 & 0xFFFF))|0 ; }; /** * @method getByKey * @param {Number} key * @return {Object} */ TupleDictionary.prototype.getByKey = function(key) { key = key|0; return this.data[key]; }; /** * @method get * @param {Number} i * @param {Number} j * @return {Number} */ TupleDictionary.prototype.get = function(i, j) { return this.data[this.getKey(i, j)]; }; /** * Set a value. * @method set * @param {Number} i * @param {Number} j * @param {Number} value */ TupleDictionary.prototype.set = function(i, j, value) { if(!value){ throw new Error("No data!"); } var key = this.getKey(i, j); // Check if key already exists if(!this.data[key]){ this.keys.push(key); } this.data[key] = value; return key; }; /** * Remove all data. * @method reset */ TupleDictionary.prototype.reset = function() { var data = this.data, keys = this.keys; var l = keys.length; while(l--) { delete data[keys[l]]; } keys.length = 0; }; /** * Copy another TupleDictionary. Note that all data in this dictionary will be removed. * @method copy * @param {TupleDictionary} dict The TupleDictionary to copy into this one. */ TupleDictionary.prototype.copy = function(dict) { this.reset(); Utils.appendArray(this.keys, dict.keys); var l = dict.keys.length; while(l--){ var key = dict.keys[l]; this.data[key] = dict.data[key]; } }; },{"./Utils":50,"__browserify_Buffer":1,"__browserify_process":2}],50:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/utils\\Utils.js",__dirname="/utils";module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){}; /** * Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * The array type to use for internal numeric computations. * @type {Array} * @static * @property ARRAY_TYPE */ Utils.ARRAY_TYPE = window.Float32Array || Array; /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.defaults = function(options, defaults){ options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; },{"__browserify_Buffer":1,"__browserify_process":2}],51:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/world\\Island.js",__dirname="/world";var Body = require('../objects/Body'); module.exports = Island; /** * An island of bodies connected with equations. * @class Island * @constructor */ function Island(){ /** * Current equations in this island. * @property equations * @type {Array} */ this.equations = []; /** * Current bodies in this island. * @property bodies * @type {Array} */ this.bodies = []; } /** * Clean this island from bodies and equations. * @method reset */ Island.prototype.reset = function(){ this.equations.length = this.bodies.length = 0; }; var bodyIds = []; /** * Get all unique bodies in this island. * @method getBodies * @return {Array} An array of Body */ Island.prototype.getBodies = function(result){ var bodies = result || [], eqs = this.equations; bodyIds.length = 0; for(var i=0; i!==eqs.length; i++){ var eq = eqs[i]; if(bodyIds.indexOf(eq.bodyA.id)===-1){ bodies.push(eq.bodyA); bodyIds.push(eq.bodyA.id); } if(bodyIds.indexOf(eq.bodyB.id)===-1){ bodies.push(eq.bodyB); bodyIds.push(eq.bodyB.id); } } return bodies; }; /** * Check if the entire island wants to sleep. * @method wantsToSleep * @return {Boolean} */ Island.prototype.wantsToSleep = function(){ for(var i=0; i<this.bodies.length; i++){ var b = this.bodies[i]; if(b.type === Body.DYNAMIC && !b.wantsToSleep){ return false; } } return true; }; /** * Make all bodies in the island sleep. * @method sleep */ Island.prototype.sleep = function(){ for(var i=0; i<this.bodies.length; i++){ var b = this.bodies[i]; b.sleep(); } return true; }; },{"../objects/Body":32,"__browserify_Buffer":1,"__browserify_process":2}],52:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/world\\IslandManager.js",__dirname="/world";var vec2 = require('../math/vec2') , Island = require('./Island') , IslandNode = require('./IslandNode') , Body = require('../objects/Body'); module.exports = IslandManager; /** * Splits the system of bodies and equations into independent islands * * @class IslandManager * @constructor * @param {Object} [options] * @extends Solver */ function IslandManager(options){ // Pooling of node objects saves some GC load this._nodePool = []; this._islandPool = []; /** * The equations to split. Manually fill this array before running .split(). * @property {Array} equations */ this.equations = []; /** * The resulting {{#crossLink "Island"}}{{/crossLink}}s. * @property {Array} islands */ this.islands = []; /** * The resulting graph nodes. * @property {Array} nodes */ this.nodes = []; /** * The node queue, used when traversing the graph of nodes. * @private * @property {Array} queue */ this.queue = []; } /** * Get an unvisited node from a list of nodes. * @static * @method getUnvisitedNode * @param {Array} nodes * @return {IslandNode|boolean} The node if found, else false. */ IslandManager.getUnvisitedNode = function(nodes){ var Nnodes = nodes.length; for(var i=0; i!==Nnodes; i++){ var node = nodes[i]; if(!node.visited && node.body.type === Body.DYNAMIC){ return node; } } return false; }; /** * Visit a node. * @method visit * @param {IslandNode} node * @param {Array} bds * @param {Array} eqs */ IslandManager.prototype.visit = function (node,bds,eqs){ bds.push(node.body); var Neqs = node.equations.length; for(var i=0; i!==Neqs; i++){ var eq = node.equations[i]; if(eqs.indexOf(eq) === -1){ // Already added? eqs.push(eq); } } }; /** * Runs the search algorithm, starting at a root node. The resulting bodies and equations will be stored in the provided arrays. * @method bfs * @param {IslandNode} root The node to start from * @param {Array} bds An array to append resulting Bodies to. * @param {Array} eqs An array to append resulting Equations to. */ IslandManager.prototype.bfs = function(root,bds,eqs){ // Reset the visit queue var queue = this.queue; queue.length = 0; // Add root node to queue queue.push(root); root.visited = true; this.visit(root,bds,eqs); // Process all queued nodes while(queue.length) { // Get next node in the queue var node = queue.pop(); // Visit unvisited neighboring nodes var child; while((child = IslandManager.getUnvisitedNode(node.neighbors))) { child.visited = true; this.visit(child,bds,eqs); // Only visit the children of this node if it's dynamic if(child.body.type === Body.DYNAMIC){ queue.push(child); } } } }; /** * Split the world into independent islands. The result is stored in .islands. * @method split * @param {World} world * @return {Array} The generated islands */ IslandManager.prototype.split = function(world){ var bodies = world.bodies, nodes = this.nodes, equations = this.equations; // Move old nodes to the node pool while(nodes.length){ this._nodePool.push(nodes.pop()); } // Create needed nodes, reuse if possible for(var i=0; i!==bodies.length; i++){ if(this._nodePool.length){ var node = this._nodePool.pop(); node.reset(); node.body = bodies[i]; nodes.push(node); } else { nodes.push(new IslandNode(bodies[i])); } } // Add connectivity data. Each equation connects 2 bodies. for(var k=0; k!==equations.length; k++){ var eq=equations[k], i=bodies.indexOf(eq.bodyA), j=bodies.indexOf(eq.bodyB), ni=nodes[i], nj=nodes[j]; ni.neighbors.push(nj); nj.neighbors.push(ni); ni.equations.push(eq); nj.equations.push(eq); } // Move old islands to the island pool var islands = this.islands; while(islands.length){ var island = islands.pop(); island.reset(); this._islandPool.push(island); } // Get islands var child; while((child = IslandManager.getUnvisitedNode(nodes))){ // Create new island var island = this._islandPool.length ? this._islandPool.pop() : new Island(); // Get all equations and bodies in this island this.bfs(child, island.bodies, island.equations); islands.push(island); } return islands; }; },{"../math/vec2":31,"../objects/Body":32,"./Island":51,"./IslandNode":53,"__browserify_Buffer":1,"__browserify_process":2}],53:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/world\\IslandNode.js",__dirname="/world";module.exports = IslandNode; /** * Holds a body and keeps track of some additional properties needed for graph traversal. * @class IslandNode * @constructor * @param {Body} body */ function IslandNode(body){ /** * The body that is contained in this node. * @property {Body} body */ this.body = body; /** * Neighboring IslandNodes * @property {Array} neighbors */ this.neighbors = []; /** * Equations connected to this node. * @property {Array} equations */ this.equations = []; /** * If this node was visiting during the graph traversal. * @property visited * @type {Boolean} */ this.visited = false; } /** * Clean this node from bodies and equations. * @method reset */ IslandNode.prototype.reset = function(){ this.equations.length = 0; this.neighbors.length = 0; this.visited = false; this.body = null; }; },{"__browserify_Buffer":1,"__browserify_process":2}],54:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},Buffer=require("__browserify_Buffer"),__filename="/world\\World.js",__dirname="/world";/* global performance */ /*jshint -W020 */ var GSSolver = require('../solver/GSSolver') , Solver = require('../solver/Solver') , NaiveBroadphase = require('../collision/NaiveBroadphase') , vec2 = require('../math/vec2') , Circle = require('../shapes/Circle') , Rectangle = require('../shapes/Rectangle') , Convex = require('../shapes/Convex') , Line = require('../shapes/Line') , Plane = require('../shapes/Plane') , Capsule = require('../shapes/Capsule') , Particle = require('../shapes/Particle') , EventEmitter = require('../events/EventEmitter') , Body = require('../objects/Body') , Shape = require('../shapes/Shape') , LinearSpring = require('../objects/LinearSpring') , Material = require('../material/Material') , ContactMaterial = require('../material/ContactMaterial') , DistanceConstraint = require('../constraints/DistanceConstraint') , Constraint = require('../constraints/Constraint') , LockConstraint = require('../constraints/LockConstraint') , RevoluteConstraint = require('../constraints/RevoluteConstraint') , PrismaticConstraint = require('../constraints/PrismaticConstraint') , GearConstraint = require('../constraints/GearConstraint') , pkg = require('../../package.json') , Broadphase = require('../collision/Broadphase') , SAPBroadphase = require('../collision/SAPBroadphase') , Narrowphase = require('../collision/Narrowphase') , Utils = require('../utils/Utils') , OverlapKeeper = require('../utils/OverlapKeeper') , IslandManager = require('./IslandManager') , RotationalSpring = require('../objects/RotationalSpring'); module.exports = World; if(typeof performance === 'undefined'){ performance = {}; } if(!performance.now){ var nowOffset = Date.now(); if (performance.timing && performance.timing.navigationStart){ nowOffset = performance.timing.navigationStart; } performance.now = function(){ return Date.now() - nowOffset; }; } /** * The dynamics world, where all bodies and constraints lives. * * @class World * @constructor * @param {Object} [options] * @param {Solver} [options.solver] Defaults to GSSolver. * @param {Array} [options.gravity] Defaults to [0,-9.78] * @param {Broadphase} [options.broadphase] Defaults to NaiveBroadphase * @param {Boolean} [options.islandSplit=false] * @param {Boolean} [options.doProfiling=false] * @extends EventEmitter * * @example * var world = new World({ * gravity: [0, -9.81], * broadphase: new SAPBroadphase() * }); */ function World(options){ EventEmitter.apply(this); options = options || {}; /** * All springs in the world. To add a spring to the world, use {{#crossLink "World/addSpring:method"}}{{/crossLink}}. * * @property springs * @type {Array} */ this.springs = []; /** * All bodies in the world. To add a body to the world, use {{#crossLink "World/addBody:method"}}{{/crossLink}}. * @property {Array} bodies */ this.bodies = []; /** * Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}. * @private * @property {Array} disabledBodyCollisionPairs */ this.disabledBodyCollisionPairs = []; /** * The solver used to satisfy constraints and contacts. Default is {{#crossLink "GSSolver"}}{{/crossLink}}. * @property {Solver} solver */ this.solver = options.solver || new GSSolver(); /** * The narrowphase to use to generate contacts. * * @property narrowphase * @type {Narrowphase} */ this.narrowphase = new Narrowphase(this); /** * The island manager of this world. * @property {IslandManager} islandManager */ this.islandManager = new IslandManager(); /** * Gravity in the world. This is applied on all bodies in the beginning of each step(). * * @property gravity * @type {Array} */ this.gravity = vec2.fromValues(0, -9.78); if(options.gravity){ vec2.copy(this.gravity, options.gravity); } /** * Gravity to use when approximating the friction max force (mu*mass*gravity). * @property {Number} frictionGravity */ this.frictionGravity = vec2.length(this.gravity) || 10; /** * Set to true if you want .frictionGravity to be automatically set to the length of .gravity. * @property {Boolean} useWorldGravityAsFrictionGravity */ this.useWorldGravityAsFrictionGravity = true; /** * If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games. * @property {Boolean} useFrictionGravityOnZeroGravity */ this.useFrictionGravityOnZeroGravity = true; /** * Whether to do timing measurements during the step() or not. * * @property doPofiling * @type {Boolean} */ this.doProfiling = options.doProfiling || false; /** * How many millisecconds the last step() took. This is updated each step if .doProfiling is set to true. * * @property lastStepTime * @type {Number} */ this.lastStepTime = 0.0; /** * The broadphase algorithm to use. * * @property broadphase * @type {Broadphase} */ this.broadphase = options.broadphase || new SAPBroadphase(); this.broadphase.setWorld(this); /** * User-added constraints. * * @property constraints * @type {Array} */ this.constraints = []; /** * Dummy default material in the world, used in .defaultContactMaterial * @property {Material} defaultMaterial */ this.defaultMaterial = new Material(); /** * The default contact material to use, if no contact material was set for the colliding materials. * @property {ContactMaterial} defaultContactMaterial */ this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial); /** * For keeping track of what time step size we used last step * @property lastTimeStep * @type {Number} */ this.lastTimeStep = 1/60; /** * Enable to automatically apply spring forces each step. * @property applySpringForces * @type {Boolean} */ this.applySpringForces = true; /** * Enable to automatically apply body damping each step. * @property applyDamping * @type {Boolean} */ this.applyDamping = true; /** * Enable to automatically apply gravity each step. * @property applyGravity * @type {Boolean} */ this.applyGravity = true; /** * Enable/disable constraint solving in each step. * @property solveConstraints * @type {Boolean} */ this.solveConstraints = true; /** * The ContactMaterials added to the World. * @property contactMaterials * @type {Array} */ this.contactMaterials = []; /** * World time. * @property time * @type {Number} */ this.time = 0.0; /** * Is true during the step(). * @property {Boolean} stepping */ this.stepping = false; /** * Bodies that are scheduled to be removed at the end of the step. * @property {Array} bodiesToBeRemoved * @private */ this.bodiesToBeRemoved = []; this.fixedStepTime = 0.0; /** * Whether to enable island splitting. Island splitting can be an advantage for many things, including solver performance. See {{#crossLink "IslandManager"}}{{/crossLink}}. * @property {Boolean} islandSplit */ this.islandSplit = typeof(options.islandSplit)!=="undefined" ? !!options.islandSplit : false; /** * Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. * @property emitImpactEvent * @type {Boolean} */ this.emitImpactEvent = true; // Id counters this._constraintIdCounter = 0; this._bodyIdCounter = 0; /** * Fired after the step(). * @event postStep */ this.postStepEvent = { type : "postStep", }; /** * Fired when a body is added to the world. * @event addBody * @param {Body} body */ this.addBodyEvent = { type : "addBody", body : null }; /** * Fired when a body is removed from the world. * @event removeBody * @param {Body} body */ this.removeBodyEvent = { type : "removeBody", body : null }; /** * Fired when a spring is added to the world. * @event addSpring * @param {Spring} spring */ this.addSpringEvent = { type : "addSpring", spring : null, }; /** * Fired when a first contact is created between two bodies. This event is fired after the step has been done. * @event impact * @param {Body} bodyA * @param {Body} bodyB */ this.impactEvent = { type: "impact", bodyA : null, bodyB : null, shapeA : null, shapeB : null, contactEquation : null, }; /** * Fired after the Broadphase has collected collision pairs in the world. * Inside the event handler, you can modify the pairs array as you like, to * prevent collisions between objects that you don't want. * @event postBroadphase * @param {Array} pairs An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase. */ this.postBroadphaseEvent = { type:"postBroadphase", pairs:null, }; /** * How to deactivate bodies during simulation. Possible modes are: {{#crossLink "World/NO_SLEEPING:property"}}World.NO_SLEEPING{{/crossLink}}, {{#crossLink "World/BODY_SLEEPING:property"}}World.BODY_SLEEPING{{/crossLink}} and {{#crossLink "World/ISLAND_SLEEPING:property"}}World.ISLAND_SLEEPING{{/crossLink}}. * If sleeping is enabled, you might need to {{#crossLink "Body/wakeUp:method"}}wake up{{/crossLink}} the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see {{#crossLink "Body/allowSleep:property"}}Body.allowSleep{{/crossLink}}. * @property sleepMode * @type {number} * @default World.NO_SLEEPING */ this.sleepMode = World.NO_SLEEPING; /** * Fired when two shapes starts start to overlap. Fired in the narrowphase, during step. * @event beginContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ this.beginContactEvent = { type:"beginContact", shapeA : null, shapeB : null, bodyA : null, bodyB : null, contactEquations : [], }; /** * Fired when two shapes stop overlapping, after the narrowphase (during step). * @event endContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ this.endContactEvent = { type:"endContact", shapeA : null, shapeB : null, bodyA : null, bodyB : null, }; /** * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver. * @event preSolve * @param {Array} contactEquations An array of contacts to be solved. * @param {Array} frictionEquations An array of friction equations to be solved. */ this.preSolveEvent = { type:"preSolve", contactEquations:null, frictionEquations:null, }; // For keeping track of overlapping shapes this.overlappingShapesLastState = { keys:[] }; this.overlappingShapesCurrentState = { keys:[] }; this.overlapKeeper = new OverlapKeeper(); } World.prototype = new Object(EventEmitter.prototype); /** * Never deactivate bodies. * @static * @property {number} NO_SLEEPING */ World.NO_SLEEPING = 1; /** * Deactivate individual bodies if they are sleepy. * @static * @property {number} BODY_SLEEPING */ World.BODY_SLEEPING = 2; /** * Deactivates bodies that are in contact, if all of them are sleepy. Note that you must enable {{#crossLink "World/islandSplit:property"}}.islandSplit{{/crossLink}} for this to work. * @static * @property {number} ISLAND_SLEEPING */ World.ISLAND_SLEEPING = 4; /** * Add a constraint to the simulation. * * @method addConstraint * @param {Constraint} c */ World.prototype.addConstraint = function(c){ this.constraints.push(c); }; /** * Add a ContactMaterial to the simulation. * @method addContactMaterial * @param {ContactMaterial} contactMaterial */ World.prototype.addContactMaterial = function(contactMaterial){ this.contactMaterials.push(contactMaterial); }; /** * Removes a contact material * * @method removeContactMaterial * @param {ContactMaterial} cm */ World.prototype.removeContactMaterial = function(cm){ var idx = this.contactMaterials.indexOf(cm); if(idx!==-1){ Utils.splice(this.contactMaterials,idx,1); } }; /** * Get a contact material given two materials * @method getContactMaterial * @param {Material} materialA * @param {Material} materialB * @return {ContactMaterial} The matching ContactMaterial, or false on fail. * @todo Use faster hash map to lookup from material id's */ World.prototype.getContactMaterial = function(materialA,materialB){ var cmats = this.contactMaterials; for(var i=0, N=cmats.length; i!==N; i++){ var cm = cmats[i]; if( (cm.materialA.id === materialA.id) && (cm.materialB.id === materialB.id) || (cm.materialA.id === materialB.id) && (cm.materialB.id === materialA.id) ){ return cm; } } return false; }; /** * Removes a constraint * * @method removeConstraint * @param {Constraint} c */ World.prototype.removeConstraint = function(c){ var idx = this.constraints.indexOf(c); if(idx!==-1){ Utils.splice(this.constraints,idx,1); } }; var step_r = vec2.create(), step_runit = vec2.create(), step_u = vec2.create(), step_f = vec2.create(), step_fhMinv = vec2.create(), step_velodt = vec2.create(), step_mg = vec2.create(), xiw = vec2.fromValues(0,0), xjw = vec2.fromValues(0,0), zero = vec2.fromValues(0,0), interpvelo = vec2.fromValues(0,0); /** * Step the physics world forward in time. * * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take. * * @method step * @param {Number} dt The fixed time step size to use. * @param {Number} [timeSinceLastCalled=0] The time elapsed since the function was last called. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call. * * @example * // fixed timestepping without interpolation * var world = new World(); * world.step(0.01); * * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World */ World.prototype.step = function(dt,timeSinceLastCalled,maxSubSteps){ maxSubSteps = maxSubSteps || 10; timeSinceLastCalled = timeSinceLastCalled || 0; if(timeSinceLastCalled === 0){ // Fixed, simple stepping this.internalStep(dt); // Increment time this.time += dt; } else { // Compute the number of fixed steps we should have taken since the last step var internalSteps = Math.floor( (this.time+timeSinceLastCalled) / dt) - Math.floor(this.time / dt); internalSteps = Math.min(internalSteps,maxSubSteps); // Do some fixed steps to catch up var t0 = performance.now(); for(var i=0; i!==internalSteps; i++){ this.internalStep(dt); if(performance.now() - t0 > dt*1000){ // We are slower than real-time. Better bail out. break; } } // Increment internal clock this.time += timeSinceLastCalled; // Compute "Left over" time step var h = this.time % dt; var h_div_dt = h/dt; for(var j=0; j!==this.bodies.length; j++){ var b = this.bodies[j]; if(b.type !== Body.STATIC && b.sleepState !== Body.SLEEPING){ // Interpolate vec2.sub(interpvelo, b.position, b.previousPosition); vec2.scale(interpvelo, interpvelo, h_div_dt); vec2.add(b.interpolatedPosition, b.position, interpvelo); b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt; } else { // For static bodies, just copy. Who else will do it? vec2.copy(b.interpolatedPosition, b.position); b.interpolatedAngle = b.angle; } } } }; var endOverlaps = []; /** * Make a fixed step. * @method internalStep * @param {number} dt * @private */ World.prototype.internalStep = function(dt){ this.stepping = true; var that = this, doProfiling = this.doProfiling, Nsprings = this.springs.length, springs = this.springs, bodies = this.bodies, g = this.gravity, solver = this.solver, Nbodies = this.bodies.length, broadphase = this.broadphase, np = this.narrowphase, constraints = this.constraints, t0, t1, fhMinv = step_fhMinv, velodt = step_velodt, mg = step_mg, scale = vec2.scale, add = vec2.add, rotate = vec2.rotate, islandManager = this.islandManager; this.overlapKeeper.tick(); this.lastTimeStep = dt; if(doProfiling){ t0 = performance.now(); } // Update approximate friction gravity. if(this.useWorldGravityAsFrictionGravity){ var gravityLen = vec2.length(this.gravity); if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ // Nonzero gravity. Use it. this.frictionGravity = gravityLen; } } // Add gravity to bodies if(this.applyGravity){ for(var i=0; i!==Nbodies; i++){ var b = bodies[i], fi = b.force; if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ continue; } vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g add(fi,fi,mg); } } // Add spring forces if(this.applySpringForces){ for(var i=0; i!==Nsprings; i++){ var s = springs[i]; s.applyForce(); } } if(this.applyDamping){ for(var i=0; i!==Nbodies; i++){ var b = bodies[i]; if(b.type === Body.DYNAMIC){ b.applyDamping(dt); } } } // Broadphase var result = broadphase.getCollisionPairs(this); // Remove ignored collision pairs var ignoredPairs = this.disabledBodyCollisionPairs; for(var i=ignoredPairs.length-2; i>=0; i-=2){ for(var j=result.length-2; j>=0; j-=2){ if( (ignoredPairs[i] === result[j] && ignoredPairs[i+1] === result[j+1]) || (ignoredPairs[i+1] === result[j] && ignoredPairs[i] === result[j+1])){ result.splice(j,2); } } } // Remove constrained pairs with collideConnected == false var Nconstraints = constraints.length; for(i=0; i!==Nconstraints; i++){ var c = constraints[i]; if(!c.collideConnected){ for(var j=result.length-2; j>=0; j-=2){ if( (c.bodyA === result[j] && c.bodyB === result[j+1]) || (c.bodyB === result[j] && c.bodyA === result[j+1])){ result.splice(j,2); } } } } // postBroadphase event this.postBroadphaseEvent.pairs = result; this.emit(this.postBroadphaseEvent); // Narrowphase np.reset(this); for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ var bi = result[i], bj = result[i+1]; // Loop over all shapes of body i for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ var si = bi.shapes[k], xi = bi.shapeOffsets[k], ai = bi.shapeAngles[k]; // All shapes of body j for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ var sj = bj.shapes[l], xj = bj.shapeOffsets[l], aj = bj.shapeAngles[l]; var cm = this.defaultContactMaterial; if(si.material && sj.material){ var tmp = this.getContactMaterial(si.material,sj.material); if(tmp){ cm = tmp; } } this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,this.frictionGravity); } } } // Wake up bodies for(var i=0; i!==Nbodies; i++){ var body = bodies[i]; if(body._wakeUpAfterNarrowphase){ body.wakeUp(); body._wakeUpAfterNarrowphase = false; } } // Emit end overlap events if(this.has('endContact')){ this.overlapKeeper.getEndOverlaps(endOverlaps); var e = this.endContactEvent; var l = endOverlaps.length; while(l--){ var data = endOverlaps[l]; e.shapeA = data.shapeA; e.shapeB = data.shapeB; e.bodyA = data.bodyA; e.bodyB = data.bodyB; this.emit(e); } } var preSolveEvent = this.preSolveEvent; preSolveEvent.contactEquations = np.contactEquations; preSolveEvent.frictionEquations = np.frictionEquations; this.emit(preSolveEvent); // update constraint equations var Nconstraints = constraints.length; for(i=0; i!==Nconstraints; i++){ constraints[i].update(); } if(np.contactEquations.length || np.frictionEquations.length || constraints.length){ if(this.islandSplit){ // Split into islands islandManager.equations.length = 0; Utils.appendArray(islandManager.equations, np.contactEquations); Utils.appendArray(islandManager.equations, np.frictionEquations); for(i=0; i!==Nconstraints; i++){ Utils.appendArray(islandManager.equations, constraints[i].equations); } islandManager.split(this); for(var i=0; i!==islandManager.islands.length; i++){ var island = islandManager.islands[i]; if(island.equations.length){ solver.solveIsland(dt,island); } } } else { // Add contact equations to solver solver.addEquations(np.contactEquations); solver.addEquations(np.frictionEquations); // Add user-defined constraint equations for(i=0; i!==Nconstraints; i++){ solver.addEquations(constraints[i].equations); } if(this.solveConstraints){ solver.solve(dt,this); } solver.removeAllEquations(); } } // Step forward for(var i=0; i!==Nbodies; i++){ var body = bodies[i]; if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ World.integrateBody(body,dt); } } // Reset force for(var i=0; i!==Nbodies; i++){ bodies[i].setZeroForce(); } if(doProfiling){ t1 = performance.now(); that.lastStepTime = t1-t0; } // Emit impact event if(this.emitImpactEvent && this.has('impact')){ var ev = this.impactEvent; for(var i=0; i!==np.contactEquations.length; i++){ var eq = np.contactEquations[i]; if(eq.firstImpact){ ev.bodyA = eq.bodyA; ev.bodyB = eq.bodyB; ev.shapeA = eq.shapeA; ev.shapeB = eq.shapeB; ev.contactEquation = eq; this.emit(ev); } } } // Sleeping update if(this.sleepMode === World.BODY_SLEEPING){ for(i=0; i!==Nbodies; i++){ bodies[i].sleepTick(this.time, false, dt); } } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ // Tell all bodies to sleep tick but dont sleep yet for(i=0; i!==Nbodies; i++){ bodies[i].sleepTick(this.time, true, dt); } // Sleep islands for(var i=0; i<this.islandManager.islands.length; i++){ var island = this.islandManager.islands[i]; if(island.wantsToSleep()){ island.sleep(); } } } this.stepping = false; // Remove bodies that are scheduled for removal if(this.bodiesToBeRemoved.length){ for(var i=0; i!==this.bodiesToBeRemoved.length; i++){ this.removeBody(this.bodiesToBeRemoved[i]); } this.bodiesToBeRemoved.length = 0; } this.emit(this.postStepEvent); }; var ib_fhMinv = vec2.create(); var ib_velodt = vec2.create(); /** * Move a body forward in time. * @static * @method integrateBody * @param {Body} body * @param {Number} dt * @todo Move to Body.prototype? */ World.integrateBody = function(body,dt){ var minv = body.invMass, f = body.force, pos = body.position, velo = body.velocity; // Save old position vec2.copy(body.previousPosition, body.position); body.previousAngle = body.angle; // Angular step if(!body.fixedRotation){ body.angularVelocity += body.angularForce * body.invInertia * dt; body.angle += body.angularVelocity * dt; } // Linear step vec2.scale(ib_fhMinv,f,dt*minv); vec2.add(velo,ib_fhMinv,velo); vec2.scale(ib_velodt,velo,dt); vec2.add(pos,pos,ib_velodt); body.aabbNeedsUpdate = true; }; /** * Runs narrowphase for the shape pair i and j. * @method runNarrowphase * @param {Narrowphase} np * @param {Body} bi * @param {Shape} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Shape} sj * @param {Array} xj * @param {Number} aj * @param {Number} mu */ World.prototype.runNarrowphase = function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){ // Check collision groups and masks if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0)){ return; } // Get world position and angle of each shape vec2.rotate(xiw, xi, bi.angle); vec2.rotate(xjw, xj, bj.angle); vec2.add(xiw, xiw, bi.position); vec2.add(xjw, xjw, bj.position); var aiw = ai + bi.angle; var ajw = aj + bj.angle; np.enableFriction = cm.friction > 0; np.frictionCoefficient = cm.friction; var reducedMass; if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ reducedMass = bj.mass; } else if(bj.type === Body.STATIC || bj.type === Body.KINEMATIC){ reducedMass = bi.mass; } else { reducedMass = (bi.mass*bj.mass)/(bi.mass+bj.mass); } np.slipForce = cm.friction*glen*reducedMass; np.restitution = cm.restitution; np.surfaceVelocity = cm.surfaceVelocity; np.frictionStiffness = cm.frictionStiffness; np.frictionRelaxation = cm.frictionRelaxation; np.stiffness = cm.stiffness; np.relaxation = cm.relaxation; np.contactSkinSize = cm.contactSkinSize; var resolver = np[si.type | sj.type], numContacts = 0; if (resolver) { var sensor = si.sensor || sj.sensor; var numFrictionBefore = np.frictionEquations.length; if (si.type < sj.type) { numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); } else { numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); } var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; if(numContacts){ if( bi.allowSleep && bi.type === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.type !== Body.STATIC ){ var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); if(speedSquaredB >= speedLimitSquaredB*2){ bi._wakeUpAfterNarrowphase = true; } } if( bj.allowSleep && bj.type === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.type !== Body.STATIC ){ var speedSquaredA = vec2.squaredLength(bi.velocity) + Math.pow(bi.angularVelocity,2); var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2); if(speedSquaredA >= speedLimitSquaredA*2){ bj._wakeUpAfterNarrowphase = true; } } this.overlapKeeper.setOverlapping(bi, si, bj, sj); if(this.has('beginContact') && this.overlapKeeper.isNewOverlap(si, sj)){ // Report new shape overlap var e = this.beginContactEvent; e.shapeA = si; e.shapeB = sj; e.bodyA = bi; e.bodyB = bj; // Reset contact equations e.contactEquations.length = 0; if(typeof(numContacts)==="number"){ for(var i=np.contactEquations.length-numContacts; i<np.contactEquations.length; i++){ e.contactEquations.push(np.contactEquations[i]); } } this.emit(e); } // divide the max friction force by the number of contacts if(typeof(numContacts)==="number" && numFrictionEquations > 1){ // Why divide by 1? for(var i=np.frictionEquations.length-numFrictionEquations; i<np.frictionEquations.length; i++){ var f = np.frictionEquations[i]; f.setSlipForce(f.getSlipForce() / numFrictionEquations); } } } } }; /** * Add a spring to the simulation * * @method addSpring * @param {Spring} s */ World.prototype.addSpring = function(s){ this.springs.push(s); this.addSpringEvent.spring = s; this.emit(this.addSpringEvent); }; /** * Remove a spring * * @method removeSpring * @param {Spring} s */ World.prototype.removeSpring = function(s){ var idx = this.springs.indexOf(s); if(idx!==-1){ Utils.splice(this.springs,idx,1); } }; /** * Add a body to the simulation * * @method addBody * @param {Body} body * * @example * var world = new World(), * body = new Body(); * world.addBody(body); * @todo What if this is done during step? */ World.prototype.addBody = function(body){ if(this.bodies.indexOf(body) === -1){ this.bodies.push(body); body.world = this; this.addBodyEvent.body = body; this.emit(this.addBodyEvent); } }; /** * Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step. * * @method removeBody * @param {Body} body */ World.prototype.removeBody = function(body){ if(this.stepping){ this.bodiesToBeRemoved.push(body); } else { body.world = null; var idx = this.bodies.indexOf(body); if(idx!==-1){ Utils.splice(this.bodies,idx,1); this.removeBodyEvent.body = body; body.resetConstraintVelocity(); this.emit(this.removeBodyEvent); } } }; /** * Get a body by its id. * @method getBodyById * @return {Body|Boolean} The body, or false if it was not found. */ World.prototype.getBodyById = function(id){ var bodies = this.bodies; for(var i=0; i<bodies.length; i++){ var b = bodies[i]; if(b.id === id){ return b; } } return false; }; /** * Disable collision between two bodies * @method disableCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.disableBodyCollision = function(bodyA,bodyB){ this.disabledBodyCollisionPairs.push(bodyA,bodyB); }; /** * Enable collisions between the given two bodies * @method enableCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.enableBodyCollision = function(bodyA,bodyB){ var pairs = this.disabledBodyCollisionPairs; for(var i=0; i<pairs.length; i+=2){ if((pairs[i] === bodyA && pairs[i+1] === bodyB) || (pairs[i+1] === bodyA && pairs[i] === bodyB)){ pairs.splice(i,2); return; } } }; function v2a(v){ if(!v){ return v; } return [v[0],v[1]]; } function extend(a,b){ for(var key in b){ a[key] = b[key]; } } function contactMaterialToJSON(cm){ return { id : cm.id, materialA : cm.materialA.id, materialB : cm.materialB.id, friction : cm.friction, restitution : cm.restitution, stiffness : cm.stiffness, relaxation : cm.relaxation, frictionStiffness : cm.frictionStiffness, frictionRelaxation : cm.frictionRelaxation, }; } /** * Resets the World, removes all bodies, constraints and springs. * * @method clear */ World.prototype.clear = function(){ this.time = 0; this.fixedStepTime = 0; // Remove all solver equations if(this.solver && this.solver.equations.length){ this.solver.removeAllEquations(); } // Remove all constraints var cs = this.constraints; for(var i=cs.length-1; i>=0; i--){ this.removeConstraint(cs[i]); } // Remove all bodies var bodies = this.bodies; for(var i=bodies.length-1; i>=0; i--){ this.removeBody(bodies[i]); } // Remove all springs var springs = this.springs; for(var i=springs.length-1; i>=0; i--){ this.removeSpring(springs[i]); } // Remove all contact materials var cms = this.contactMaterials; for(var i=cms.length-1; i>=0; i--){ this.removeContactMaterial(cms[i]); } World.apply(this); }; /** * Get a copy of this World instance * @method clone * @return {World} */ World.prototype.clone = function(){ var world = new World(); world.fromJSON(this.toJSON()); return world; }; var hitTest_tmp1 = vec2.create(), hitTest_zero = vec2.fromValues(0,0), hitTest_tmp2 = vec2.fromValues(0,0); /** * Test if a world point overlaps bodies * @method hitTest * @param {Array} worldPoint Point to use for intersection tests * @param {Array} bodies A list of objects to check for intersection * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. * @return {Array} Array of bodies that overlap the point */ World.prototype.hitTest = function(worldPoint,bodies,precision){ precision = precision || 0; // Create a dummy particle body with a particle shape to test against the bodies var pb = new Body({ position:worldPoint }), ps = new Particle(), px = worldPoint, pa = 0, x = hitTest_tmp1, zero = hitTest_zero, tmp = hitTest_tmp2; pb.addShape(ps); var n = this.narrowphase, result = []; // Check bodies for(var i=0, N=bodies.length; i!==N; i++){ var b = bodies[i]; for(var j=0, NS=b.shapes.length; j!==NS; j++){ var s = b.shapes[j], offset = b.shapeOffsets[j] || zero, angle = b.shapeAngles[j] || 0.0; // Get shape world position + angle vec2.rotate(x, offset, b.angle); vec2.add(x, x, b.position); var a = angle + b.angle; if( (s instanceof Circle && n.circleParticle (b,s,x,a, pb,ps,px,pa, true)) || (s instanceof Convex && n.particleConvex (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Plane && n.particlePlane (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Capsule && n.particleCapsule (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Particle && vec2.squaredLength(vec2.sub(tmp,x,worldPoint)) < precision*precision) ){ result.push(b); } } } return result; }; /** * Sets the Equation parameters for all constraints and contact materials. * @method setGlobalEquationParameters * @param {object} [parameters] * @param {Number} [parameters.relaxation] * @param {Number} [parameters.stiffness] */ World.prototype.setGlobalEquationParameters = function(parameters){ parameters = parameters || {}; // Set for all constraints for(var i=0; i !== this.constraints.length; i++){ var c = this.constraints[i]; for(var j=0; j !== c.equations.length; j++){ var eq = c.equations[j]; if(typeof(parameters.stiffness) !== "undefined"){ eq.stiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ eq.relaxation = parameters.relaxation; } eq.needsUpdate = true; } } // Set for all contact materials for(var i=0; i !== this.contactMaterials.length; i++){ var c = this.contactMaterials[i]; if(typeof(parameters.stiffness) !== "undefined"){ c.stiffness = parameters.stiffness; c.frictionStiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ c.relaxation = parameters.relaxation; c.frictionRelaxation = parameters.relaxation; } } // Set for default contact material var c = this.defaultContactMaterial; if(typeof(parameters.stiffness) !== "undefined"){ c.stiffness = parameters.stiffness; c.frictionStiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ c.relaxation = parameters.relaxation; c.frictionRelaxation = parameters.relaxation; } }; /** * Set the stiffness for all equations and contact materials. * @method setGlobalStiffness * @param {Number} stiffness */ World.prototype.setGlobalStiffness = function(stiffness){ this.setGlobalEquationParameters({ stiffness: stiffness }); }; /** * Set the relaxation for all equations and contact materials. * @method setGlobalRelaxation * @param {Number} relaxation */ World.prototype.setGlobalRelaxation = function(relaxation){ this.setGlobalEquationParameters({ relaxation: relaxation }); }; },{"../../package.json":8,"../collision/Broadphase":10,"../collision/NaiveBroadphase":12,"../collision/Narrowphase":13,"../collision/SAPBroadphase":14,"../constraints/Constraint":15,"../constraints/DistanceConstraint":16,"../constraints/GearConstraint":17,"../constraints/LockConstraint":18,"../constraints/PrismaticConstraint":19,"../constraints/RevoluteConstraint":20,"../events/EventEmitter":27,"../material/ContactMaterial":28,"../material/Material":29,"../math/vec2":31,"../objects/Body":32,"../objects/LinearSpring":33,"../objects/RotationalSpring":34,"../shapes/Capsule":37,"../shapes/Circle":38,"../shapes/Convex":39,"../shapes/Line":41,"../shapes/Particle":42,"../shapes/Plane":43,"../shapes/Rectangle":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":48,"../utils/Utils":50,"./IslandManager":52,"__browserify_Buffer":1,"__browserify_process":2}]},{},[36]) (36) }); ;; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ // Add an extra properties to p2 that we need p2.Body.prototype.parent = null; p2.Spring.prototype.parent = null; /** * This is your main access to the P2 Physics World. * From here you can create materials, listen for events and add bodies into the physics simulation. * * @class Phaser.Physics.P2 * @constructor * @param {Phaser.Game} game - Reference to the current game instance. * @param {object} [config] - Physics configuration object passed in from the game constructor. */ Phaser.Physics.P2 = function (game, config) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; if (typeof config === 'undefined' || !config.hasOwnProperty('gravity') || !config.hasOwnProperty('broadphase')) { config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; } /** * @property {object} config - The p2 World configuration object. * @protected */ this.config = config; /** * @property {p2.World} world - The p2 World in which the simulation is run. * @protected */ this.world = new p2.World(this.config); /** * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. * @default */ this.frameRate = 1 / 60; /** * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. * @default */ this.useElapsedTime = false; /** * @property {boolean} paused - The paused state of the P2 World. * @default */ this.paused = false; /** * @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials. * @protected */ this.materials = []; /** * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. */ this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); /** * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. */ this.walls = { left: null, right: null, top: null, bottom: null }; /** * @property {Phaser.Signal} onBodyAdded - Dispatched when a new Body is added to the World. */ this.onBodyAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onBodyRemoved - Dispatched when a Body is removed from the World. */ this.onBodyRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringAdded - Dispatched when a new Spring is added to the World. */ this.onSpringAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringRemoved - Dispatched when a Spring is removed from the World. */ this.onSpringRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintAdded - Dispatched when a new Constraint is added to the World. */ this.onConstraintAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintRemoved - Dispatched when a Constraint is removed from the World. */ this.onConstraintRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialAdded - Dispatched when a new ContactMaterial is added to the World. */ this.onContactMaterialAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialRemoved - Dispatched when a ContactMaterial is removed from the World. */ this.onContactMaterialRemoved = new Phaser.Signal(); /** * @property {function} postBroadphaseCallback - A postBroadphase callback. */ this.postBroadphaseCallback = null; /** * @property {object} callbackContext - The context under which the callbacks are fired. */ this.callbackContext = null; /** * @property {Phaser.Signal} onBeginContact - Dispatched when a first contact is created between two bodies. This event is fired before the step has been done. */ this.onBeginContact = new Phaser.Signal(); /** * @property {Phaser.Signal} onEndContact - Dispatched when final contact occurs between two bodies. This event is fired before the step has been done. */ this.onEndContact = new Phaser.Signal(); // Pixel to meter function overrides if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) { this.mpx = config.mpx; this.mpxi = config.mpxi; this.pxm = config.pxm; this.pxmi = config.pxmi; } // Hook into the World events this.world.on("beginContact", this.beginContactHandler, this); this.world.on("endContact", this.endContactHandler, this); /** * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. */ this.collisionGroups = []; /** * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. */ this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); /** * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. */ this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); /** * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. */ this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); /** * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. */ this.boundsCollidesWith = []; /** * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. * @private */ this._toRemove = []; /** * @property {number} _collisionGroupID - Internal var. * @private */ this._collisionGroupID = 2; // By default we want everything colliding with everything this.setBoundsToWorld(true, true, true, true, false); }; Phaser.Physics.P2.prototype = { /** * This will add a P2 Physics body into the removal list for the next step. * * @method Phaser.Physics.P2#removeBodyNextStep * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. */ removeBodyNextStep: function (body) { this._toRemove.push(body); }, /** * Called at the start of the core update loop. Purges flagged bodies from the world. * * @method Phaser.Physics.P2#preUpdate */ preUpdate: function () { var i = this._toRemove.length; while (i--) { this.removeBody(this._toRemove[i]); } this._toRemove.length = 0; }, /** * This will create a P2 Physics body on the given game object or array of game objects. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. * * @method Phaser.Physics.P2#enable * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. * @param {boolean} [debug=false] - Create a debug object to go with this body? * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. */ enable: function (object, debug, children) { if (typeof debug === 'undefined') { debug = false; } if (typeof children === 'undefined') { children = true; } var i = 1; if (Array.isArray(object)) { i = object.length; while (i--) { if (object[i] instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object[i].children, debug, children); } else { this.enableBody(object[i], debug); if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) { this.enable(object[i], debug, true); } } } } else { if (object instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object.children, debug, children); } else { this.enableBody(object, debug); if (children && object.hasOwnProperty('children') && object.children.length > 0) { this.enable(object.children, debug, true); } } } }, /** * Creates a P2 Physics body on the given game object. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. * * @method Phaser.Physics.P2#enableBody * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. * @param {boolean} debug - Create a debug object to go with this body? */ enableBody: function (object, debug) { if (object.hasOwnProperty('body') && object.body === null) { object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1); object.body.debug = debug; object.anchor.set(0.5); } }, /** * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. * * @method Phaser.Physics.P2#setImpactEvents * @param {boolean} state - Set to true to enable impact events, or false to disable. */ setImpactEvents: function (state) { if (state) { this.world.on("impact", this.impactHandler, this); } else { this.world.off("impact", this.impactHandler, this); } }, /** * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. * Returning `true` from the callback will ensure they are checked in the narrowphase. * * @method Phaser.Physics.P2#setPostBroadphaseCallback * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. * @param {object} context - The context under which the callback will be fired. */ setPostBroadphaseCallback: function (callback, context) { this.postBroadphaseCallback = callback; this.callbackContext = context; if (callback !== null) { this.world.on("postBroadphase", this.postBroadphaseHandler, this); } else { this.world.off("postBroadphase", this.postBroadphaseHandler, this); } }, /** * Internal handler for the postBroadphase event. * * @method Phaser.Physics.P2#postBroadphaseHandler * @private * @param {object} event - The event data. */ postBroadphaseHandler: function (event) { var i = event.pairs.length; if (this.postBroadphaseCallback && i > 0) { while (i -= 2) { if (event.pairs[i].parent && event.pairs[i+1].parent && !this.postBroadphaseCallback.call(this.callbackContext, event.pairs[i].parent, event.pairs[i+1].parent)) { event.pairs.splice(i, 2); } } } }, /** * Handles a p2 impact event. * * @method Phaser.Physics.P2#impactHandler * @private * @param {object} event - The event data. */ impactHandler: function (event) { if (event.bodyA.parent && event.bodyB.parent) { // Body vs. Body callbacks var a = event.bodyA.parent; var b = event.bodyB.parent; if (a._bodyCallbacks[event.bodyB.id]) { a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB); } if (b._bodyCallbacks[event.bodyA.id]) { b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA); } // Body vs. Group callbacks if (a._groupCallbacks[event.shapeB.collisionGroup]) { a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB); } if (b._groupCallbacks[event.shapeA.collisionGroup]) { b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA); } } }, /** * Handles a p2 begin contact event. * * @method Phaser.Physics.P2#beginContactHandler * @param {object} event - The event data. */ beginContactHandler: function (event) { this.onBeginContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB, event.contactEquations); if (event.bodyA.parent) { event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB, event.contactEquations); } if (event.bodyB.parent) { event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA, event.contactEquations); } }, /** * Handles a p2 end contact event. * * @method Phaser.Physics.P2#endContactHandler * @param {object} event - The event data. */ endContactHandler: function (event) { this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); if (event.bodyA.parent) { event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB); } if (event.bodyB.parent) { event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA); } }, /** * Sets the bounds of the Physics world to match the Game.World dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics#setBoundsToWorld * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) { this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup); }, /** * Sets the given material against the 4 bounds of this World. * * @method Phaser.Physics#setWorldMaterial * @param {Phaser.Physics.P2.Material} material - The material to set. * @param {boolean} [left=true] - If true will set the material on the left bounds wall. * @param {boolean} [right=true] - If true will set the material on the right bounds wall. * @param {boolean} [top=true] - If true will set the material on the top bounds wall. * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. */ setWorldMaterial: function (material, left, right, top, bottom) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (left && this.walls.left) { this.walls.left.shapes[0].material = material; } if (right && this.walls.right) { this.walls.right.shapes[0].material = material; } if (top && this.walls.top) { this.walls.top.shapes[0].material = material; } if (bottom && this.walls.bottom) { this.walls.bottom.shapes[0].material = material; } }, /** * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. * If you start to use your own collision groups then your objects will no longer collide with the bounds. * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. * * @method Phaser.Physics.P2#updateBoundsCollisionGroup * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ updateBoundsCollisionGroup: function (setCollisionGroup) { var mask = this.everythingCollisionGroup.mask; if (typeof setCollisionGroup === 'undefined') { mask = this.boundsCollisionGroup.mask; } if (this.walls.left) { this.walls.left.shapes[0].collisionGroup = mask; } if (this.walls.right) { this.walls.right.shapes[0].collisionGroup = mask; } if (this.walls.top) { this.walls.top.shapes[0].collisionGroup = mask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionGroup = mask; } }, /** * Sets the bounds of the Physics world to match the given world pixel dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics.P2#setBounds * @param {number} x - The x coordinate of the top-left corner of the bounds. * @param {number} y - The y coordinate of the top-left corner of the bounds. * @param {number} width - The width of the bounds. * @param {number} height - The height of the bounds. * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (typeof setCollisionGroup === 'undefined') { setCollisionGroup = true; } if (this.walls.left) { this.world.removeBody(this.walls.left); } if (this.walls.right) { this.world.removeBody(this.walls.right); } if (this.walls.top) { this.world.removeBody(this.walls.top); } if (this.walls.bottom) { this.world.removeBody(this.walls.bottom); } if (left) { this.walls.left = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: 1.5707963267948966 }); this.walls.left.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.left.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.left); } if (right) { this.walls.right = new p2.Body({ mass: 0, position: [ this.pxmi(x + width), this.pxmi(y) ], angle: -1.5707963267948966 }); this.walls.right.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.right.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.right); } if (top) { this.walls.top = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: -3.141592653589793 }); this.walls.top.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.top.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.top); } if (bottom) { this.walls.bottom = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y + height) ] }); this.walls.bottom.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.bottom.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.bottom); } }, /** * Pauses the P2 World independent of the game pause state. * * @method Phaser.Physics.P2#pause */ pause: function() { this.paused = true; }, /** * Resumes a paused P2 World. * * @method Phaser.Physics.P2#resume */ resume: function() { this.paused = false; }, /** * Internal P2 update loop. * * @method Phaser.Physics.P2#update */ update: function () { // Do nothing when the pysics engine was paused before if (this.paused) { return; } if (this.useElapsedTime) { this.world.step(this.game.time.physicsElapsed); } else { this.world.step(this.frameRate); } }, /** * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. * * @method Phaser.Physics.P2#clear */ clear: function () { this.world.clear(); this.world.off("beginContact", this.beginContactHandler, this); this.world.off("endContact", this.endContactHandler, this); this.postBroadphaseCallback = null; this.callbackContext = null; this.impactCallback = null; this.collisionGroups = []; this._toRemove = []; this._collisionGroupID = 2; this.boundsCollidesWith = []; }, /** * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. * * @method Phaser.Physics.P2#destroy */ destroy: function () { this.clear(); this.game = null; }, /** * Add a body to the world. * * @method Phaser.Physics.P2#addBody * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. * @return {boolean} True if the Body was added successfully, otherwise false. */ addBody: function (body) { if (body.data.world) { return false; } else { this.world.addBody(body.data); this.onBodyAdded.dispatch(body); return true; } }, /** * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. * * @method Phaser.Physics.P2#removeBody * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. * @return {Phaser.Physics.P2.Body} The Body that was removed. */ removeBody: function (body) { if (body.data.world == this.world) { this.world.removeBody(body.data); this.onBodyRemoved.dispatch(body); } return body; }, /** * Adds a Spring to the world. * * @method Phaser.Physics.P2#addSpring * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. * @return {Phaser.Physics.P2.Spring} The Spring that was added. */ addSpring: function (spring) { if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) { this.world.addSpring(spring.data); } else { this.world.addSpring(spring); } this.onSpringAdded.dispatch(spring); return spring; }, /** * Removes a Spring from the world. * * @method Phaser.Physics.P2#removeSpring * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. * @return {Phaser.Physics.P2.Spring} The Spring that was removed. */ removeSpring: function (spring) { if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) { this.world.removeSpring(spring.data); } else { this.world.removeSpring(spring); } this.onSpringRemoved.dispatch(spring); return spring; }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createDistanceConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} distance - The distance to keep between the bodies. * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.DistanceConstraint} The constraint */ createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce)); } }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createGearConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [angle=0] - The relative angle * @param {number} [ratio=1] - The gear ratio. * @return {Phaser.Physics.P2.GearConstraint} The constraint */ createGearConstraint: function (bodyA, bodyB, angle, ratio) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this, bodyA, bodyB, angle, ratio)); } }, /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * The pivot points are given in world (pixel) coordinates. * * @method Phaser.Physics.P2#createRevoluteConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint */ createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot)); } }, /** * Locks the relative position between two bodies. * * @method Phaser.Physics.P2#createLockConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.LockConstraint} The constraint */ createLockConstraint: function (bodyA, bodyB, offset, angle, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this, bodyA, bodyB, offset, angle, maxForce)); } }, /** * Constraint that only allows bodies to move along a line, relative to each other. * See http://www.iforce2d.net/b2dtut/joints-prismatic * * @method Phaser.Physics.P2#createPrismaticConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint */ createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce)); } }, /** * Adds a Constraint to the world. * * @method Phaser.Physics.P2#addConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. */ addConstraint: function (constraint) { this.world.addConstraint(constraint); this.onConstraintAdded.dispatch(constraint); return constraint; }, /** * Removes a Constraint from the world. * * @method Phaser.Physics.P2#removeConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. */ removeConstraint: function (constraint) { this.world.removeConstraint(constraint); this.onConstraintRemoved.dispatch(constraint); return constraint; }, /** * Adds a Contact Material to the world. * * @method Phaser.Physics.P2#addContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. */ addContactMaterial: function (material) { this.world.addContactMaterial(material); this.onContactMaterialAdded.dispatch(material); return material; }, /** * Removes a Contact Material from the world. * * @method Phaser.Physics.P2#removeContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. */ removeContactMaterial: function (material) { this.world.removeContactMaterial(material); this.onContactMaterialRemoved.dispatch(material); return material; }, /** * Gets a Contact Material based on the two given Materials. * * @method Phaser.Physics.P2#getContactMaterial * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. */ getContactMaterial: function (materialA, materialB) { return this.world.getContactMaterial(materialA, materialB); }, /** * Sets the given Material against all Shapes owned by all the Bodies in the given array. * * @method Phaser.Physics.P2#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. * @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on. */ setMaterial: function (material, bodies) { var i = bodies.length; while (i--) { bodies[i].setMaterial(material); } }, /** * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. * * @method Phaser.Physics.P2#createMaterial * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. */ createMaterial: function (name, body) { name = name || ''; var material = new Phaser.Physics.P2.Material(name); this.materials.push(material); if (typeof body !== 'undefined') { body.setMaterial(material); } return material; }, /** * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. * * @method Phaser.Physics.P2#createContactMaterial * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {object} [options] - Material options object. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. */ createContactMaterial: function (materialA, materialB, options) { if (typeof materialA === 'undefined') { materialA = this.createMaterial(); } if (typeof materialB === 'undefined') { materialB = this.createMaterial(); } var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); return this.addContactMaterial(contact); }, /** * Populates and returns an array with references to of all current Bodies in the world. * * @method Phaser.Physics.P2#getBodies * @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world. */ getBodies: function () { var output = []; var i = this.world.bodies.length; while (i--) { output.push(this.world.bodies[i].parent); } return output; }, /** * Checks the given object to see if it has a p2.Body and if so returns it. * * @method Phaser.Physics.P2#getBody * @param {object} object - The object to check for a p2.Body on. * @return {p2.Body} The p2.Body, or null if not found. */ getBody: function (object) { if (object instanceof p2.Body) { // Native p2 body return object; } else if (object instanceof Phaser.Physics.P2.Body) { // Phaser P2 Body return object.data; } else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) { // Sprite, TileSprite, etc return object.body.data; } return null; }, /** * Populates and returns an array of all current Springs in the world. * * @method Phaser.Physics.P2#getSprings * @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world. */ getSprings: function () { var output = []; var i = this.world.springs.length; while (i--) { output.push(this.world.springs[i].parent); } return output; }, /** * Populates and returns an array of all current Constraints in the world. * * @method Phaser.Physics.P2#getConstraints * @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world. */ getConstraints: function () { var output = []; var i = this.world.constraints.length; while (i--) { output.push(this.world.constraints[i].parent); } return output; }, /** * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. * * @method Phaser.Physics.P2#hitTest * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. * @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. * @return {Array} Array of bodies that overlap the point. */ hitTest: function (worldPoint, bodies, precision, filterStatic) { if (typeof bodies === 'undefined') { bodies = this.world.bodies; } if (typeof precision === 'undefined') { precision = 5; } if (typeof filterStatic === 'undefined') { filterStatic = false; } var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ]; var query = []; var i = bodies.length; while (i--) { if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.type === p2.Body.STATIC)) { query.push(bodies[i].data); } else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) { query.push(bodies[i]); } else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) { query.push(bodies[i].body.data); } } return this.world.hitTest(physicsPosition, query, precision); }, /** * Converts the current world into a JSON object. * * @method Phaser.Physics.P2#toJSON * @return {object} A JSON representation of the world. */ toJSON: function () { return this.world.toJSON(); }, /** * Creates a new Collision Group and optionally applies it to the given object. * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. * * @method Phaser.Physics.P2#createCollisionGroup * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. */ createCollisionGroup: function (object) { var bitmask = Math.pow(2, this._collisionGroupID); if (this.walls.left) { this.walls.left.shapes[0].collisionMask = this.walls.left.shapes[0].collisionMask | bitmask; } if (this.walls.right) { this.walls.right.shapes[0].collisionMask = this.walls.right.shapes[0].collisionMask | bitmask; } if (this.walls.top) { this.walls.top.shapes[0].collisionMask = this.walls.top.shapes[0].collisionMask | bitmask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionMask = this.walls.bottom.shapes[0].collisionMask | bitmask; } this._collisionGroupID++; var group = new Phaser.Physics.P2.CollisionGroup(bitmask); this.collisionGroups.push(group); if (object) { this.setCollisionGroup(object, group); } return group; }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. * * @method Phaser.Physics.P2y#setCollisionGroup * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. */ setCollisionGroup: function (object, group) { if (object instanceof Phaser.Group) { for (var i = 0; i < object.total; i++) { if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) { object.children[i].body.setCollisionGroup(group); } } } else { object.body.setCollisionGroup(group); } }, /** * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @method Phaser.Physics.P2#createSpring * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @return {Phaser.Physics.P2.Spring} The spring */ createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Spring, invalid body objects given'); } else { return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); } }, /** * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @method Phaser.Physics.P2#createRotationalSpring * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @return {Phaser.Physics.P2.RotationalSpring} The spring */ createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Rotational Spring, invalid body objects given'); } else { return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); } }, /** * Creates a new Body and adds it to the World. * * @method Phaser.Physics.P2#createBody * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {Phaser.Physics.P2.Body} The body */ createBody: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Creates a new Particle and adds it to the World. * * @method Phaser.Physics.P2#createParticle * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. */ createParticle: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world. * Note that the polylines must be created in such a way that they can withstand polygon decomposition. * * @method Phaser.Physics.P2#convertCollisionObjects * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. * @return {array} An array of the Phaser.Physics.Body objects that have been created. */ convertCollisionObjects: function (map, layer, addToWorld) { if (typeof addToWorld === 'undefined') { addToWorld = true; } var output = []; for (var i = 0, len = map.collision[layer].length; i < len; i++) { // name: json.layers[i].objects[v].name, // x: json.layers[i].objects[v].x, // y: json.layers[i].objects[v].y, // width: json.layers[i].objects[v].width, // height: json.layers[i].objects[v].height, // visible: json.layers[i].objects[v].visible, // properties: json.layers[i].objects[v].properties, // polyline: json.layers[i].objects[v].polyline var object = map.collision[layer][i]; var body = this.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline); if (body) { output.push(body); } } return output; }, /** * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. * * @method Phaser.Physics.P2#clearTilemapLayerBodies * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. */ clearTilemapLayerBodies: function (map, layer) { layer = map.getLayer(layer); var i = map.layers[layer].bodies.length; while (i--) { map.layers[layer].bodies[i].destroy(); } map.layers[layer].bodies.length = 0; }, /** * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. * Every time you call this method it will destroy any previously created bodies and remove them from the world. * Therefore understand it's a very expensive operation and not to be done in a core game update loop. * * @method Phaser.Physics.P2#convertTilemap * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. */ convertTilemap: function (map, layer, addToWorld, optimize) { layer = map.getLayer(layer); if (typeof addToWorld === 'undefined') { addToWorld = true; } if (typeof optimize === 'undefined') { optimize = true; } // If the bodies array is already populated we need to nuke it this.clearTilemapLayerBodies(map, layer); var width = 0; var sx = 0; var sy = 0; for (var y = 0, h = map.layers[layer].height; y < h; y++) { width = 0; for (var x = 0, w = map.layers[layer].width; x < w; x++) { var tile = map.layers[layer].data[y][x]; if (tile && tile.index > -1 && tile.collides) { if (optimize) { var right = map.getTileRight(layer, x, y); if (width === 0) { sx = tile.x * tile.width; sy = tile.y * tile.height; width = tile.width; } if (right && right.collides) { width += tile.width; } else { var body = this.createBody(sx, sy, 0, false); body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); width = 0; } } else { var body = this.createBody(tile.x * tile.width, tile.y * tile.height, 0, false); body.addRectangle(tile.width, tile.height, tile.width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); } } } } return map.layers[layer].bodies; }, /** * Convert p2 physics value (meters) to pixel scale. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpx * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpx: function (v) { return v *= 20; }, /** * Convert pixel value to p2 physics scale (meters). * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxm * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxm: function (v) { return v * 0.05; }, /** * Convert p2 physics value (meters) to pixel scale and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpxi * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpxi: function (v) { return v *= -20; }, /** * Convert pixel value to p2 physics scale (meters) and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxmi * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxmi: function (v) { return v * -0.05; } }; /** * @name Phaser.Physics.P2#friction * @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { get: function () { return this.world.defaultContactMaterial.friction; }, set: function (value) { this.world.defaultContactMaterial.friction = value; } }); /** * @name Phaser.Physics.P2#restitution * @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { get: function () { return this.world.defaultContactMaterial.restitution; }, set: function (value) { this.world.defaultContactMaterial.restitution = value; } }); /** * @name Phaser.Physics.P2#contactMaterial * @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. */ Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { get: function () { return this.world.defaultContactMaterial; }, set: function (value) { this.world.defaultContactMaterial = value; } }); /** * @name Phaser.Physics.P2#applySpringForces * @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { get: function () { return this.world.applySpringForces; }, set: function (value) { this.world.applySpringForces = value; } }); /** * @name Phaser.Physics.P2#applyDamping * @property {boolean} applyDamping - Enable to automatically apply body damping each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { get: function () { return this.world.applyDamping; }, set: function (value) { this.world.applyDamping = value; } }); /** * @name Phaser.Physics.P2#applyGravity * @property {boolean} applyGravity - Enable to automatically apply gravity each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { get: function () { return this.world.applyGravity; }, set: function (value) { this.world.applyGravity = value; } }); /** * @name Phaser.Physics.P2#solveConstraints * @property {boolean} solveConstraints - Enable/disable constraint solving in each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { get: function () { return this.world.solveConstraints; }, set: function (value) { this.world.solveConstraints = value; } }); /** * @name Phaser.Physics.P2#time * @property {boolean} time - The World time. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "time", { get: function () { return this.world.time; } }); /** * @name Phaser.Physics.P2#emitImpactEvent * @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. */ Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { get: function () { return this.world.emitImpactEvent; }, set: function (value) { this.world.emitImpactEvent = value; } }); /** * How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. * If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. * @name Phaser.Physics.P2#sleepMode * @property {number} sleepMode */ Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { get: function () { return this.world.sleepMode; }, set: function (value) { this.world.sleepMode = value; } }); /** * @name Phaser.Physics.P2#total * @property {number} total - The total number of bodies in the world. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "total", { get: function () { return this.world.bodies.length; } }); /* jshint noarg: false */ /** * @author Georgios Kaleadis https://github.com/georgiee * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Allow to access a list of created fixture (coming from Body#addPhaserPolygon) * which itself parse the input from PhysicsEditor with the custom phaser exporter. * You can access fixtures of a Body by a group index or even by providing a fixture Key. * You can set the fixture key and also the group index for a fixture in PhysicsEditor. * This gives you the power to create a complex body built of many fixtures and modify them * during runtime (to remove parts, set masks, categories & sensor properties) * * @class Phaser.Physics.P2.FixtureList * @constructor * @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) */ Phaser.Physics.P2.FixtureList = function (list) { if (!Array.isArray(list)) { list = [list]; } this.rawList = list; this.init(); this.parse(this.rawList); }; Phaser.Physics.P2.FixtureList.prototype = { /** * @method Phaser.Physics.P2.FixtureList#init */ init: function () { /** * @property {object} namedFixtures - Collect all fixtures with a key * @private */ this.namedFixtures = {}; /** * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group * @private */ this.groupedFixtures = []; /** * @property {Array} allFixtures - This is a list of everything in this collection * @private */ this.allFixtures = []; }, /** * @method Phaser.Physics.P2.FixtureList#setCategory * @param {number} bit - The bit to set as the collision group. * @param {string} fixtureKey - Only apply to the fixture with the given key. */ setCategory: function (bit, fixtureKey) { var setter = function(fixture) { fixture.collisionGroup = bit; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setMask * @param {number} bit - The bit to set as the collision mask * @param {string} fixtureKey - Only apply to the fixture with the given key */ setMask: function (bit, fixtureKey) { var setter = function(fixture) { fixture.collisionMask = bit; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setSensor * @param {boolean} value - sensor true or false * @param {string} fixtureKey - Only apply to the fixture with the given key */ setSensor: function (value, fixtureKey) { var setter = function(fixture) { fixture.sensor = value; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setMaterial * @param {Object} material - The contact material for a fixture * @param {string} fixtureKey - Only apply to the fixture with the given key */ setMaterial: function (material, fixtureKey) { var setter = function(fixture) { fixture.material = material; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * Accessor to get either a list of specified fixtures by key or the whole fixture list * * @method Phaser.Physics.P2.FixtureList#getFixtures * @param {array} keys - A list of fixture keys */ getFixtures: function (keys) { var fixtures = []; if (keys) { if (!(keys instanceof Array)) { keys = [keys]; } var self = this; keys.forEach(function(key) { if (self.namedFixtures[key]) { fixtures.push(self.namedFixtures[key]); } }); return this.flatten(fixtures); } else { return this.allFixtures; } }, /** * Accessor to get either a single fixture by its key. * * @method Phaser.Physics.P2.FixtureList#getFixtureByKey * @param {string} key - The key of the fixture. */ getFixtureByKey: function (key) { return this.namedFixtures[key]; }, /** * Accessor to get a group of fixtures by its group index. * * @method Phaser.Physics.P2.FixtureList#getGroup * @param {number} groupID - The group index. */ getGroup: function (groupID) { return this.groupedFixtures[groupID]; }, /** * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon * * @method Phaser.Physics.P2.FixtureList#parse */ parse: function () { var key, value, _ref, _results; _ref = this.rawList; _results = []; for (key in _ref) { value = _ref[key]; if (!isNaN(key - 0)) { this.groupedFixtures[key] = this.groupedFixtures[key] || []; this.groupedFixtures[key] = this.groupedFixtures[key].concat(value); } else { this.namedFixtures[key] = this.flatten(value); } _results.push(this.allFixtures = this.flatten(this.groupedFixtures)); } }, /** * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. * * @method Phaser.Physics.P2.FixtureList#flatten * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. */ flatten: function (array) { var result, self; result = []; self = arguments.callee; array.forEach(function(item) { return Array.prototype.push.apply(result, (Array.isArray(item) ? self(item) : [item])); }); return result; } }; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. * * @class Phaser.Physics.P2.PointProxy * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {any} destination - The object to bind to. */ Phaser.Physics.P2.PointProxy = function (world, destination) { this.world = world; this.destination = destination; }; Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; /** * @name Phaser.Physics.P2.PointProxy#x * @property {number} x - The x property of this PointProxy get and set in pixels. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { get: function () { return this.world.mpx(this.destination[0]); }, set: function (value) { this.destination[0] = this.world.pxm(value); } }); /** * @name Phaser.Physics.P2.PointProxy#y * @property {number} y - The y property of this PointProxy get and set in pixels. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { get: function () { return this.world.mpx(this.destination[1]); }, set: function (value) { this.destination[1] = this.world.pxm(value); } }); /** * @name Phaser.Physics.P2.PointProxy#mx * @property {number} mx - The x property of this PointProxy get and set in meters. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { get: function () { return this.destination[0]; }, set: function (value) { this.destination[0] = value; } }); /** * @name Phaser.Physics.P2.PointProxy#my * @property {number} my - The x property of this PointProxy get and set in meters. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { get: function () { return this.destination[1]; }, set: function (value) { this.destination[1] = value; } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. * * @class Phaser.Physics.P2.InversePointProxy * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {any} destination - The object to bind to. */ Phaser.Physics.P2.InversePointProxy = function (world, destination) { this.world = world; this.destination = destination; }; Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; /** * @name Phaser.Physics.P2.InversePointProxy#x * @property {number} x - The x property of this InversePointProxy get and set in pixels. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { get: function () { return this.world.mpxi(this.destination[0]); }, set: function (value) { this.destination[0] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.InversePointProxy#y * @property {number} y - The y property of this InversePointProxy get and set in pixels. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { get: function () { return this.world.mpxi(this.destination[1]); }, set: function (value) { this.destination[1] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.InversePointProxy#mx * @property {number} mx - The x property of this InversePointProxy get and set in meters. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { get: function () { return this.destination[0]; }, set: function (value) { this.destination[0] = -value; } }); /** * @name Phaser.Physics.P2.InversePointProxy#my * @property {number} my - The y property of this InversePointProxy get and set in meters. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { get: function () { return this.destination[1]; }, set: function (value) { this.destination[1] = -value; } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. * These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. * In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. * By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. * Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. * Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. * * @class Phaser.Physics.P2.Body * @constructor * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. * @param {number} [x=0] - The x coordinate of this Body. * @param {number} [y=0] - The y coordinate of this Body. * @param {number} [mass=1] - The default mass of this Body (0 = static). */ Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { sprite = sprite || null; x = x || 0; y = y || 0; if (typeof mass === 'undefined') { mass = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; /** * @property {Phaser.Physics.P2} world - Local reference to the P2 World. */ this.world = game.physics.p2; /** * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. */ this.sprite = sprite; /** * @property {number} type - The type of physics system this body belongs to. */ this.type = Phaser.Physics.P2JS; /** * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. */ this.offset = new Phaser.Point(); /** * @property {p2.Body} data - The p2 Body data. * @protected */ this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); this.data.parent = this; /** * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. */ this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); /** * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. */ this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); /** * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. */ this.gravity = new Phaser.Point(); /** * Dispatched when a first contact is created between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 4 parameters: The body it is in contact with, the shape from this body that caused the contact, the shape from the contact body and the contact equation data array. * @property {Phaser.Signal} onBeginContact */ this.onBeginContact = new Phaser.Signal(); /** * Dispatched when contact ends between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 3 parameters: The body it is in contact with, the shape from this body that caused the contact and the shape from the contact body. * @property {Phaser.Signal} onEndContact */ this.onEndContact = new Phaser.Signal(); /** * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. */ this.collidesWith = []; /** * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. */ this.removeNextStep = false; /** * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. */ this.debugBody = null; /** * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. * @private */ this._collideWorldBounds = true; /** * @property {object} _bodyCallbacks - Array of Body callbacks. * @private */ this._bodyCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Body callback contexts. * @private */ this._bodyCallbackContext = {}; /** * @property {object} _groupCallbacks - Array of Group callbacks. * @private */ this._groupCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. * @private */ this._groupCallbackContext = {}; // Set-up the default shape if (sprite) { this.setRectangleFromSprite(sprite); if (sprite.exists) { this.game.physics.p2.addBody(this); } } }; Phaser.Physics.P2.Body.prototype = { /** * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createBodyCallback * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createBodyCallback: function (object, callback, callbackContext) { var id = -1; if (object['id']) { id = object.id; } else if (object['body']) { id = object.body.id; } if (id > -1) { if (callback === null) { delete (this._bodyCallbacks[id]); delete (this._bodyCallbackContext[id]); } else { this._bodyCallbacks[id] = callback; this._bodyCallbackContext[id] = callbackContext; } } }, /** * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * This callback will only fire if this Body has been assigned a collision group. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createGroupCallback * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createGroupCallback: function (group, callback, callbackContext) { if (callback === null) { delete (this._groupCallbacks[group.mask]); delete (this._groupCallbacksContext[group.mask]); } else { this._groupCallbacks[group.mask] = callback; this._groupCallbackContext[group.mask] = callbackContext; } }, /** * Gets the collision bitmask from the groups this body collides with. * * @method Phaser.Physics.P2.Body#getCollisionMask * @return {number} The bitmask. */ getCollisionMask: function () { var mask = 0; if (this._collideWorldBounds) { mask = this.game.physics.p2.boundsCollisionGroup.mask; } for (var i = 0; i < this.collidesWith.length; i++) { mask = mask | this.collidesWith[i].mask; } return mask; }, /** * Updates the collisionMask. * * @method Phaser.Physics.P2.Body#updateCollisionMask * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ updateCollisionMask: function (shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * This also resets the collisionMask. * * @method Phaser.Physics.P2.Body#setCollisionGroup * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ setCollisionGroup: function (group, shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionGroup = group.mask; this.data.shapes[i].collisionMask = mask; } } else { shape.collisionGroup = group.mask; shape.collisionMask = mask; } }, /** * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. * * @method Phaser.Physics.P2.Body#clearCollision * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. */ clearCollision: function (clearGroup, clearMask, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { if (clearGroup) { this.data.shapes[i].collisionGroup = null; } if (clearMask) { this.data.shapes[i].collisionMask = null; } } } else { if (clearGroup) { shape.collisionGroup = null; } if (clearMask) { shape.collisionMask = null; } } if (clearGroup) { this.collidesWith.length = 0; } }, /** * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. * * @method Phaser.Physics.P2.Body#collides * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. * @param {object} [callbackContext] - The context under which the callback will be called. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. */ collides: function (group, callback, callbackContext, shape) { if (Array.isArray(group)) { for (var i = 0; i < group.length; i++) { if (this.collidesWith.indexOf(group[i]) === -1) { this.collidesWith.push(group[i]); if (callback) { this.createGroupCallback(group[i], callback, callbackContext); } } } } else { if (this.collidesWith.indexOf(group) === -1) { this.collidesWith.push(group); if (callback) { this.createGroupCallback(group, callback, callbackContext); } } } var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Moves the shape offsets so their center of mass becomes the body center of mass. * * @method Phaser.Physics.P2.Body#adjustCenterOfMass */ adjustCenterOfMass: function () { this.data.adjustCenterOfMass(); }, /** * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. * * @method Phaser.Physics.P2.Body#applyDamping * @param {number} dt - Current time step. */ applyDamping: function (dt) { this.data.applyDamping(dt); }, /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * * @method Phaser.Physics.P2.Body#applyForce * @param {Float32Array|Array} force - The force vector to add. * @param {number} worldX - The world x point to apply the force on. * @param {number} worldY - The world y point to apply the force on. */ applyForce: function (force, worldX, worldY) { this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); }, /** * Sets the force on the body to zero. * * @method Phaser.Physics.P2.Body#setZeroForce */ setZeroForce: function () { this.data.setZeroForce(); }, /** * If this Body is dynamic then this will zero its angular velocity. * * @method Phaser.Physics.P2.Body#setZeroRotation */ setZeroRotation: function () { this.data.angularVelocity = 0; }, /** * If this Body is dynamic then this will zero its velocity on both axis. * * @method Phaser.Physics.P2.Body#setZeroVelocity */ setZeroVelocity: function () { this.data.velocity[0] = 0; this.data.velocity[1] = 0; }, /** * Sets the Body damping and angularDamping to zero. * * @method Phaser.Physics.P2.Body#setZeroDamping */ setZeroDamping: function () { this.data.damping = 0; this.data.angularDamping = 0; }, /** * Transform a world point to local body frame. * * @method Phaser.Physics.P2.Body#toLocalFrame * @param {Float32Array|Array} out - The vector to store the result in. * @param {Float32Array|Array} worldPoint - The input world vector. */ toLocalFrame: function (out, worldPoint) { return this.data.toLocalFrame(out, worldPoint); }, /** * Transform a local point to world frame. * * @method Phaser.Physics.P2.Body#toWorldFrame * @param {Array} out - The vector to store the result in. * @param {Array} localPoint - The input local vector. */ toWorldFrame: function (out, localPoint) { return this.data.toWorldFrame(out, localPoint); }, /** * This will rotate the Body by the given speed to the left (counter-clockwise). * * @method Phaser.Physics.P2.Body#rotateLeft * @param {number} speed - The speed at which it should rotate. */ rotateLeft: function (speed) { this.data.angularVelocity = this.world.pxm(-speed); }, /** * This will rotate the Body by the given speed to the left (clockwise). * * @method Phaser.Physics.P2.Body#rotateRight * @param {number} speed - The speed at which it should rotate. */ rotateRight: function (speed) { this.data.angularVelocity = this.world.pxm(speed); }, /** * Moves the Body forwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveForward * @param {number} speed - The speed at which it should move forwards. */ moveForward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = magnitude * Math.cos(angle); this.data.velocity[1] = magnitude * Math.sin(angle); }, /** * Moves the Body backwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveBackward * @param {number} speed - The speed at which it should move backwards. */ moveBackward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = -(magnitude * Math.cos(angle)); this.data.velocity[1] = -(magnitude * Math.sin(angle)); }, /** * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#thrust * @param {number} speed - The speed at which it should thrust. */ thrust: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] += magnitude * Math.cos(angle); this.data.force[1] += magnitude * Math.sin(angle); }, /** * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#reverse * @param {number} speed - The speed at which it should reverse. */ reverse: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] -= magnitude * Math.cos(angle); this.data.force[1] -= magnitude * Math.sin(angle); }, /** * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveLeft * @param {number} speed - The speed at which it should move to the left, in pixels per second. */ moveLeft: function (speed) { this.data.velocity[0] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveRight * @param {number} speed - The speed at which it should move to the right, in pixels per second. */ moveRight: function (speed) { this.data.velocity[0] = this.world.pxmi(speed); }, /** * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveUp * @param {number} speed - The speed at which it should move up, in pixels per second. */ moveUp: function (speed) { this.data.velocity[1] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveDown * @param {number} speed - The speed at which it should move down, in pixels per second. */ moveDown: function (speed) { this.data.velocity[1] = this.world.pxmi(speed); }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#preUpdate * @protected */ preUpdate: function () { if (this.removeNextStep) { this.removeFromWorld(); this.removeNextStep = false; } }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#postUpdate * @protected */ postUpdate: function () { this.sprite.x = this.world.mpxi(this.data.position[0]); this.sprite.y = this.world.mpxi(this.data.position[1]); if (!this.fixedRotation) { this.sprite.rotation = this.data.angle; } }, /** * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. * * @method Phaser.Physics.P2.Body#reset * @param {number} x - The new x position of the Body. * @param {number} y - The new x position of the Body. * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. */ reset: function (x, y, resetDamping, resetMass) { if (typeof resetDamping === 'undefined') { resetDamping = false; } if (typeof resetMass === 'undefined') { resetMass = false; } this.setZeroForce(); this.setZeroVelocity(); this.setZeroRotation(); if (resetDamping) { this.setZeroDamping(); } if (resetMass) { this.mass = 1; } this.x = x; this.y = y; }, /** * Adds this physics body to the world. * * @method Phaser.Physics.P2.Body#addToWorld */ addToWorld: function () { if (this.game.physics.p2._toRemove) { for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) { if (this.game.physics.p2._toRemove[i] === this) { this.game.physics.p2._toRemove.splice(i, 1); } } } if (this.data.world !== this.game.physics.p2.world) { this.game.physics.p2.addBody(this); } }, /** * Removes this physics body from the world. * * @method Phaser.Physics.P2.Body#removeFromWorld */ removeFromWorld: function () { if (this.data.world === this.game.physics.p2.world) { this.game.physics.p2.removeBodyNextStep(this); } }, /** * Destroys this Body and all references it holds to other objects. * * @method Phaser.Physics.P2.Body#destroy */ destroy: function () { this.removeFromWorld(); this.clearShapes(); this._bodyCallbacks = {}; this._bodyCallbackContext = {}; this._groupCallbacks = {}; this._groupCallbackContext = {}; if (this.debugBody) { this.debugBody.destroy(); } this.debugBody = null; this.sprite.body = null; this.sprite = null; }, /** * Removes all Shapes from this Body. * * @method Phaser.Physics.P2.Body#clearShapes */ clearShapes: function () { var i = this.data.shapes.length; while (i--) { this.data.removeShape(this.data.shapes[i]); } this.shapeChanged(); }, /** * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#addShape * @param {p2.Shape} shape - The shape to add to the body. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Shape} The shape that was added to the body. */ addShape: function (shape, offsetX, offsetY, rotation) { if (typeof offsetX === 'undefined') { offsetX = 0; } if (typeof offsetY === 'undefined') { offsetY = 0; } if (typeof rotation === 'undefined') { rotation = 0; } this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); this.shapeChanged(); return shape; }, /** * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Circle} The Circle shape that was added to the Body. */ addCircle: function (radius, offsetX, offsetY, rotation) { var shape = new p2.Circle(this.world.pxm(radius)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addRectangle * @param {number} width - The width of the rectangle in pixels. * @param {number} height - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ addRectangle: function (width, height, offsetX, offsetY, rotation) { var shape = new p2.Rectangle(this.world.pxm(width), this.world.pxm(height)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addPlane * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Plane} The Plane shape that was added to the Body. */ addPlane: function (offsetX, offsetY, rotation) { var shape = new p2.Plane(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addParticle * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Particle} The Particle shape that was added to the Body. */ addParticle: function (offsetX, offsetY, rotation) { var shape = new p2.Particle(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Line shape to this Body. * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addLine * @param {number} length - The length of this line (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Line} The Line shape that was added to the Body. */ addLine: function (length, offsetX, offsetY, rotation) { var shape = new p2.Line(this.world.pxm(length)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Capsule shape to this Body. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCapsule * @param {number} length - The distance between the end points in pixels. * @param {number} radius - Radius of the capsule in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Capsule} The Capsule shape that was added to the Body. */ addCapsule: function (length, radius, offsetX, offsetY, rotation) { var shape = new p2.Capsule(this.world.pxm(length), this.world.pxm(radius)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. * * @method Phaser.Physics.P2.Body#addPolygon * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {boolean} True on success, else false. */ addPolygon: function (options, points) { options = options || {}; if (!Array.isArray(points)) { points = Array.prototype.slice.call(arguments, 1); } var path = []; // Did they pass in a single array of points? if (points.length === 1 && Array.isArray(points[0])) { path = points[0].slice(0); } else if (Array.isArray(points[0])) { path = points.slice(); } else if (typeof points[0] === 'number') { // We've a list of numbers for (var i = 0, len = points.length; i < len; i += 2) { path.push([points[i], points[i + 1]]); } } // top and tail var idx = path.length - 1; if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) { path.pop(); } // Now process them into p2 values for (var p = 0; p < path.length; p++) { path[p][0] = this.world.pxmi(path[p][0]); path[p][1] = this.world.pxmi(path[p][1]); } var result = this.data.fromPolygon(path, options); this.shapeChanged(); return result; }, /** * Remove a shape from the body. Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#removeShape * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. * @return {boolean} True if the shape was found and removed, else false. */ removeShape: function (shape) { var result = this.data.removeShape(shape); this.shapeChanged(); return result; }, /** * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. * * @method Phaser.Physics.P2.Body#setCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. */ setCircle: function (radius, offsetX, offsetY, rotation) { this.clearShapes(); return this.addCircle(radius, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. * * @method Phaser.Physics.P2.Body#setRectangle * @param {number} [width=16] - The width of the rectangle in pixels. * @param {number} [height=16] - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangle: function (width, height, offsetX, offsetY, rotation) { if (typeof width === 'undefined') { width = 16; } if (typeof height === 'undefined') { height = 16; } this.clearShapes(); return this.addRectangle(width, height, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. * If no Sprite is given it defaults to using the parent of this Body. * * @method Phaser.Physics.P2.Body#setRectangleFromSprite * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangleFromSprite: function (sprite) { if (typeof sprite === 'undefined') { sprite = this.sprite; } this.clearShapes(); return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); }, /** * Adds the given Material to all Shapes that belong to this Body. * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. * * @method Phaser.Physics.P2.Body#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. */ setMaterial: function (material, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].material = material; } } else { shape.material = material; } }, /** * Updates the debug draw if any body shapes change. * * @method Phaser.Physics.P2.Body#shapeChanged */ shapeChanged: function() { if (this.debugBody) { this.debugBody.draw(); } }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * The shape data format is based on the custom phaser export in. * * @method Phaser.Physics.P2.Body#addPhaserPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. */ addPhaserPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); var createdFixtures = []; // Cycle through the fixtures for (var i = 0; i < data.length; i++) { var fixtureData = data[i]; var shapesOfFixture = this.addFixture(fixtureData); // Always add to a group createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); // if (unique) fixture key is provided if (fixtureData.fixtureKey) { createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; } } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return createdFixtures; }, /** * Add a polygon fixture. This is used during #loadPolygon. * * @method Phaser.Physics.P2.Body#addFixture * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. * @return {array} An array containing the generated shapes for the given polygon. */ addFixture: function (fixtureData) { var generatedShapes = []; if (fixtureData.circle) { var shape = new p2.Circle(this.world.pxm(fixtureData.circle.radius)); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; var offset = p2.vec2.create(); offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); this.data.addShape(shape, offset); generatedShapes.push(shape); } else { var polygons = fixtureData.polygons; var cm = p2.vec2.create(); for (var i = 0; i < polygons.length; i++) { var shapes = polygons[i]; var vertices = []; for (var s = 0; s < shapes.length; s += 2) { vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); } var shape = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== shape.vertices.length; j++) { var v = shape.vertices[j]; p2.vec2.sub(v, v, shape.centerOfMass); } p2.vec2.scale(cm, shape.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); shape.updateTriangles(); shape.updateCenterOfMass(); shape.updateBoundingRadius(); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; this.data.addShape(shape, cm); generatedShapes.push(shape); } } return generatedShapes; }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * * @method Phaser.Physics.P2.Body#loadPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @return {boolean} True on success, else false. */ loadPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); // We've multiple Convex shapes, they should be CCW automatically var cm = p2.vec2.create(); for (var i = 0; i < data.length; i++) { var vertices = []; for (var s = 0; s < data[i].shape.length; s += 2) { vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]); } var c = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== c.vertices.length; j++) { var v = c.vertices[j]; p2.vec2.sub(v, v, c.centerOfMass); } p2.vec2.scale(cm, c.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); this.data.addShape(c, cm); } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return true; } }; Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; /** * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. * @property DYNAMIC * @type {Number} * @static */ Phaser.Physics.P2.Body.DYNAMIC = 1; /** * Static body. Static bodies do not move, and they do not respond to forces or collision. * @property STATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.STATIC = 2; /** * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. * @property KINEMATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.KINEMATIC = 4; /** * @name Phaser.Physics.P2.Body#static * @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { get: function () { return (this.data.type === Phaser.Physics.P2.Body.STATIC); }, set: function (value) { if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) { this.data.type = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) { this.data.type = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } } }); /** * @name Phaser.Physics.P2.Body#dynamic * @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { get: function () { return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); }, set: function (value) { if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) { this.data.type = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) { this.data.type = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#kinematic * @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { get: function () { return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); }, set: function (value) { if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) { this.data.type = Phaser.Physics.P2.Body.KINEMATIC; this.mass = 4; } else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) { this.data.type = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#allowSleep * @property {boolean} allowSleep - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { get: function () { return this.data.allowSleep; }, set: function (value) { if (value !== this.data.allowSleep) { this.data.allowSleep = value; } } }); /** * The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. * If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#angle * @property {number} angle - The angle of this Body in degrees. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { get: function() { return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); }, set: function(value) { this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#angularDamping * @property {number} angularDamping - The angular damping acting acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { get: function () { return this.data.angularDamping; }, set: function (value) { this.data.angularDamping = value; } }); /** * @name Phaser.Physics.P2.Body#angularForce * @property {number} angularForce - The angular force acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { get: function () { return this.data.angularForce; }, set: function (value) { this.data.angularForce = value; } }); /** * @name Phaser.Physics.P2.Body#angularVelocity * @property {number} angularVelocity - The angular velocity of the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { get: function () { return this.data.angularVelocity; }, set: function (value) { this.data.angularVelocity = value; } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#damping * @property {number} damping - The linear damping acting on the body in the velocity direction. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { get: function () { return this.data.damping; }, set: function (value) { this.data.damping = value; } }); /** * @name Phaser.Physics.P2.Body#fixedRotation * @property {boolean} fixedRotation - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { get: function () { return this.data.fixedRotation; }, set: function (value) { if (value !== this.data.fixedRotation) { this.data.fixedRotation = value; } } }); /** * @name Phaser.Physics.P2.Body#inertia * @property {number} inertia - The inertia of the body around the Z axis.. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { get: function () { return this.data.inertia; }, set: function (value) { this.data.inertia = value; } }); /** * @name Phaser.Physics.P2.Body#mass * @property {number} mass - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { get: function () { return this.data.mass; }, set: function (value) { if (value !== this.data.mass) { this.data.mass = value; this.data.updateMassProperties(); } } }); /** * @name Phaser.Physics.P2.Body#motionState * @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { get: function () { return this.data.type; }, set: function (value) { if (value !== this.data.type) { this.data.type = value; } } }); /** * The angle of the Body in radians. * If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#rotation * @property {number} rotation - The angle of this Body in radians. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { get: function() { return this.data.angle; }, set: function(value) { this.data.angle = value; } }); /** * @name Phaser.Physics.P2.Body#sleepSpeedLimit * @property {number} sleepSpeedLimit - . */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { get: function () { return this.data.sleepSpeedLimit; }, set: function (value) { this.data.sleepSpeedLimit = value; } }); /** * @name Phaser.Physics.P2.Body#x * @property {number} x - The x coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { get: function () { return this.world.mpxi(this.data.position[0]); }, set: function (value) { this.data.position[0] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#y * @property {number} y - The y coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { get: function () { return this.world.mpxi(this.data.position[1]); }, set: function (value) { this.data.position[1] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#id * @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. * @readonly */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { get: function () { return this.data.id; } }); /** * @name Phaser.Physics.P2.Body#debug * @property {boolean} debug - Enable or disable debug drawing of this body */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { get: function () { return (this.debugBody !== null); }, set: function (value) { if (value && !this.debugBody) { // This will be added to the global space this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); } else if (!value && this.debugBody) { this.debugBody.destroy(); this.debugBody = null; } } }); /** * A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. * Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. * Also note that when you set this it will only effect Body shapes that already exist. If you then add further shapes to your Body * after setting this it will *not* proactively set them to collide with the bounds. * * @name Phaser.Physics.P2.Body#collideWorldBounds * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { get: function () { return this._collideWorldBounds; }, set: function (value) { if (value && !this._collideWorldBounds) { this._collideWorldBounds = true; this.updateCollisionMask(); } else if (!value && this._collideWorldBounds) { this._collideWorldBounds = false; this.updateCollisionMask(); } } }); /** * @author George https://github.com/georgiee * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Draws a P2 Body to a Graphics instance for visual debugging. * Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. * So use sparingly and rarely (if ever) in production code. * * @class Phaser.Physics.P2.BodyDebug * @constructor * @extends Phaser.Group * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. * @param {object} settings - Settings object. */ Phaser.Physics.P2.BodyDebug = function(game, body, settings) { Phaser.Group.call(this, game); /** * @property {object} defaultSettings - Default debug settings. * @private */ var defaultSettings = { pixelsPerLengthUnit: 20, debugPolygons: false, lineWidth: 1, alpha: 0.5 }; this.settings = Phaser.Utils.extend(defaultSettings, settings); /** * @property {number} ppu - Pixels per Length Unit. */ this.ppu = this.settings.pixelsPerLengthUnit; this.ppu = -1 * this.ppu; /** * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. */ this.body = body; /** * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. */ this.canvas = new Phaser.Graphics(game); this.canvas.alpha = this.settings.alpha; this.add(this.canvas); this.draw(); }; Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; Phaser.Utils.extend(Phaser.Physics.P2.BodyDebug.prototype, { /** * Core update. * * @method Phaser.Physics.P2.BodyDebug#update */ update: function() { this.updateSpriteTransform(); }, /** * Core update. * * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform */ updateSpriteTransform: function() { this.position.x = this.body.position[0] * this.ppu; this.position.y = this.body.position[1] * this.ppu; return this.rotation = this.body.angle; }, /** * Draws the P2 shapes to the Graphics object. * * @method Phaser.Physics.P2.BodyDebug#draw */ draw: function() { var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; obj = this.body; sprite = this.canvas; sprite.clear(); color = parseInt(this.randomPastelHex(), 16); lineColor = 0xff0000; lw = this.lineWidth; if (obj instanceof p2.Body && obj.shapes.length) { var l = obj.shapes.length; i = 0; while (i !== l) { child = obj.shapes[i]; offset = obj.shapeOffsets[i]; angle = obj.shapeAngles[i]; offset = offset || 0; angle = angle || 0; if (child instanceof p2.Circle) { this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); } else if (child instanceof p2.Convex) { verts = []; vrot = p2.vec2.create(); for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j) { v = child.vertices[j]; p2.vec2.rotate(vrot, v, angle); verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]); } this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]); } else if (child instanceof p2.Plane) { this.drawPlane(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, color, lineColor, lw * 5, lw * 10, lw * 10, this.ppu * 100, angle); } else if (child instanceof p2.Line) { this.drawLine(sprite, child.length * this.ppu, lineColor, lw); } else if (child instanceof p2.Rectangle) { this.drawRectangle(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); } i++; } } }, /** * Draws the P2 shapes to the Graphics object. * * @method Phaser.Physics.P2.BodyDebug#draw */ drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth, color, 1); g.beginFill(fillColor); g.drawRect(x - w / 2, y - h / 2, w, h); }, /** * Draws a P2 Circle shape. * * @method Phaser.Physics.P2.BodyDebug#drawCircle */ drawCircle: function(g, x, y, angle, radius, color, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0xffffff; } g.lineStyle(lineWidth, 0x000000, 1); g.beginFill(color, 1.0); g.drawCircle(x, y, -radius); g.endFill(); g.moveTo(x, y); g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); }, /** * Draws a P2 Line shape. * * @method Phaser.Physics.P2.BodyDebug#drawCircle */ drawLine: function(g, len, color, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth * 5, color, 1); g.moveTo(-len / 2, 0); g.lineTo(len / 2, 0); }, /** * Draws a P2 Convex shape. * * @method Phaser.Physics.P2.BodyDebug#drawConvex */ drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } if (!debug) { g.lineStyle(lineWidth, color, 1); g.beginFill(fillColor); i = 0; while (i !== verts.length) { v = verts[i]; x = v[0]; y = v[1]; if (i === 0) { g.moveTo(x, -y); } else { g.lineTo(x, -y); } i++; } g.endFill(); if (verts.length > 2) { g.moveTo(verts[verts.length - 1][0], -verts[verts.length - 1][1]); return g.lineTo(verts[0][0], -verts[0][1]); } } else { colors = [0xff0000, 0x00ff00, 0x0000ff]; i = 0; while (i !== verts.length + 1) { v0 = verts[i % verts.length]; v1 = verts[(i + 1) % verts.length]; x0 = v0[0]; y0 = v0[1]; x1 = v1[0]; y1 = v1[1]; g.lineStyle(lineWidth, colors[i % colors.length], 1); g.moveTo(x0, -y0); g.lineTo(x1, -y1); g.drawCircle(x0, -y0, lineWidth * 2); i++; } g.lineStyle(lineWidth, 0x000000, 1); return g.drawCircle(offset[0], offset[1], lineWidth * 2); } }, /** * Draws a P2 Path. * * @method Phaser.Physics.P2.BodyDebug#drawPath */ drawPath: function(g, path, color, fillColor, lineWidth) { var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth, color, 1); if (typeof fillColor === "number") { g.beginFill(fillColor); } lastx = null; lasty = null; i = 0; while (i < path.length) { v = path[i]; x = v[0]; y = v[1]; if (x !== lastx || y !== lasty) { if (i === 0) { g.moveTo(x, y); } else { p1x = lastx; p1y = lasty; p2x = x; p2y = y; p3x = path[(i + 1) % path.length][0]; p3y = path[(i + 1) % path.length][1]; area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); if (area !== 0) { g.lineTo(x, y); } } lastx = x; lasty = y; } i++; } if (typeof fillColor === "number") { g.endFill(); } if (path.length > 2 && typeof fillColor === "number") { g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); g.lineTo(path[0][0], path[0][1]); } }, /** * Draws a P2 Plane shape. * * @method Phaser.Physics.P2.BodyDebug#drawPlane */ drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { var max, xd, yd; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0xffffff; } g.lineStyle(lineWidth, lineColor, 11); g.beginFill(color); max = maxLength; g.moveTo(x0, -x1); xd = x0 + Math.cos(angle) * this.game.width; yd = x1 + Math.sin(angle) * this.game.height; g.lineTo(xd, -yd); g.moveTo(x0, -x1); xd = x0 + Math.cos(angle) * -this.game.width; yd = x1 + Math.sin(angle) * -this.game.height; g.lineTo(xd, -yd); }, /** * Picks a random pastel color. * * @method Phaser.Physics.P2.BodyDebug#randomPastelHex */ randomPastelHex: function() { var blue, green, mix, red; mix = [255, 255, 255]; red = Math.floor(Math.random() * 256); green = Math.floor(Math.random() * 256); blue = Math.floor(Math.random() * 256); red = Math.floor((red + 3 * mix[0]) / 4); green = Math.floor((green + 3 * mix[1]) / 4); blue = Math.floor((blue + 3 * mix[2]) / 4); return this.rgbToHex(red, green, blue); }, /** * Converts from RGB to Hex. * * @method Phaser.Physics.P2.BodyDebug#rgbToHex */ rgbToHex: function(r, g, b) { return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); }, /** * Component to hex conversion. * * @method Phaser.Physics.P2.BodyDebug#componentToHex */ componentToHex: function(c) { var hex; hex = c.toString(16); if (hex.len === 2) { return hex; } else { return hex + '0'; } } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @class Phaser.Physics.P2.Spring * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. */ Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; if (typeof restLength === 'undefined') { restLength = 1; } if (typeof stiffness === 'undefined') { stiffness = 100; } if (typeof damping === 'undefined') { damping = 1; } restLength = world.pxm(restLength); var options = { restLength: restLength, stiffness: stiffness, damping: damping }; if (typeof worldA !== 'undefined' && worldA !== null) { options.worldAnchorA = [ world.pxm(worldA[0]), world.pxm(worldA[1]) ]; } if (typeof worldB !== 'undefined' && worldB !== null) { options.worldAnchorB = [ world.pxm(worldB[0]), world.pxm(worldB[1]) ]; } if (typeof localA !== 'undefined' && localA !== null) { options.localAnchorA = [ world.pxm(localA[0]), world.pxm(localA[1]) ]; } if (typeof localB !== 'undefined' && localB !== null) { options.localAnchorB = [ world.pxm(localB[0]), world.pxm(localB[1]) ]; } /** * @property {p2.LinearSpring} data - The actual p2 spring object. */ this.data = new p2.LinearSpring(bodyA, bodyB, options); this.data.parent = this; }; Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @class Phaser.Physics.P2.RotationalSpring * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. */ Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; if (typeof restAngle === 'undefined') { restAngle = null; } if (typeof stiffness === 'undefined') { stiffness = 100; } if (typeof damping === 'undefined') { damping = 1; } if (restAngle) { restAngle = world.pxm(restAngle); } var options = { restAngle: restAngle, stiffness: stiffness, damping: damping }; /** * @property {p2.RotationalSpring} data - The actual p2 spring object. */ this.data = new p2.RotationalSpring(bodyA, bodyB, options); this.data.parent = this; }; Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A P2 Material. * * \o/ ~ "Because I'm a Material girl" * * @class Phaser.Physics.P2.Material * @constructor * @param {string} name - The user defined name given to this Material. */ Phaser.Physics.P2.Material = function (name) { /** * @property {string} name - The user defined name given to this Material. * @default */ this.name = name; p2.Material.call(this); }; Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype); Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Defines a physics material * * @class Phaser.Physics.P2.ContactMaterial * @constructor * @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. * @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. * @param {object} [options] - Additional configuration options. */ Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { /** * @property {number} id - The contact material identifier. */ /** * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. */ /** * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. */ /** * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. */ /** * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. */ /** * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generate. */ /** * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generate. */ /** * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generate. */ /** * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generate. */ /** * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. */ p2.ContactMaterial.call(this, materialA, materialB, options); }; Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype); Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Collision Group * * @class Phaser.Physics.P2.CollisionGroup * @constructor * @param {number} bitmask - The CollisionGroup bitmask. */ Phaser.Physics.P2.CollisionGroup = function (bitmask) { /** * @property {number} mask - The CollisionGroup bitmask. */ this.mask = bitmask; }; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A constraint that tries to keep the distance between two bodies constant. * * @class Phaser.Physics.P2.DistanceConstraint * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} distance - The distance to keep between the bodies. * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. * @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. */ Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { if (typeof distance === 'undefined') { distance = 100; } if (typeof localAnchorA === 'undefined') { localAnchorA = [0, 0]; } if (typeof localAnchorB === 'undefined') { localAnchorB = [0, 0]; } if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; distance = world.pxm(distance); localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; p2.DistanceConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * * @class Phaser.Physics.P2.GearConstraint * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} [angle=0] - The relative angle * @param {number} [ratio=1] - The gear ratio. */ Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { if (typeof angle === 'undefined') { angle = 0; } if (typeof ratio === 'undefined') { ratio = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; var options = { angle: angle, ratio: ratio }; p2.GearConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.GearConstraint.prototype = Object.create(p2.GearConstraint.prototype); Phaser.Physics.P2.GearConstraint.prototype.constructor = Phaser.Physics.P2.GearConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Locks the relative position between two bodies. * * @class Phaser.Physics.P2.LockConstraint * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { if (typeof offset === 'undefined') { offset = [0, 0]; } if (typeof angle === 'undefined') { angle = 0; } if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; offset = [ world.pxm(offset[0]), world.pxm(offset[1]) ]; var options = { localOffsetB: offset, localAngleB: angle, maxForce: maxForce }; p2.LockConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.LockConstraint.prototype = Object.create(p2.LockConstraint.prototype); Phaser.Physics.P2.LockConstraint.prototype.constructor = Phaser.Physics.P2.LockConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * * @class Phaser.Physics.P2.PrismaticConstraint * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { if (typeof lockRotation === 'undefined') { lockRotation = true; } if (typeof anchorA === 'undefined') { anchorA = [0, 0]; } if (typeof anchorB === 'undefined') { anchorB = [0, 0]; } if (typeof axis === 'undefined') { axis = [0, 0]; } if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; anchorA = [ world.pxmi(anchorA[0]), world.pxmi(anchorA[1]) ]; anchorB = [ world.pxmi(anchorB[0]), world.pxmi(anchorB[1]) ]; var options = { localAnchorA: anchorA, localAnchorB: anchorB, localAxisA: axis, maxForce: maxForce, disableRotationalLock: !lockRotation }; p2.PrismaticConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.PrismaticConstraint.prototype = Object.create(p2.PrismaticConstraint.prototype); Phaser.Physics.P2.PrismaticConstraint.prototype.constructor = Phaser.Physics.P2.PrismaticConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * The pivot points are given in world (pixel) coordinates. * * @class Phaser.Physics.P2.RevoluteConstraint * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {p2.Body} bodyB - Second connected body. * @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. */ Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } if (typeof worldPivot === 'undefined') { worldPivot = null; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; if (worldPivot) { worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; } var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; p2.RevoluteConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint;
features/remote-poller-gwt/src/main/resources/org/opennms/features/poller/remote/gwt/public/openlayers/lib/OpenLayers/Control/Panel.js
roskens/opennms-pre-github
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Control.js */ /** * Class: OpenLayers.Control.Panel * The Panel control is a container for other controls. With it toolbars * may be composed. * * Inherits from: * - <OpenLayers.Control> */ OpenLayers.Control.Panel = OpenLayers.Class(OpenLayers.Control, { /** * Property: controls * {Array(<OpenLayers.Control>)} */ controls: null, /** * APIProperty: autoActivate * {Boolean} Activate the control when it is added to a map. Default is * true. */ autoActivate: true, /** * APIProperty: defaultControl * {<OpenLayers.Control>} The control which is activated when the control is * activated (turned on), which also happens at instantiation. * If <saveState> is true, <defaultControl> will be nullified after the * first activation of the panel. */ defaultControl: null, /** * APIProperty: saveState * {Boolean} If set to true, the active state of this panel's controls will * be stored on panel deactivation, and restored on reactivation. Default * is false. */ saveState: false, /** * Property: activeState * {Object} stores the active state of this panel's controls. */ activeState: null, /** * Constructor: OpenLayers.Control.Panel * Create a new control panel. * * Each control in the panel is represented by an icon. When clicking * on an icon, the <activateControl> method is called. * * Specific properties for controls on a panel: * type - {Number} One of <OpenLayers.Control.TYPE_TOOL>, * <OpenLayers.Control.TYPE_TOGGLE>, <OpenLayers.Control.TYPE_BUTTON>. * If not provided, <OpenLayers.Control.TYPE_TOOL> is assumed. * title - {string} Text displayed when mouse is over the icon that * represents the control. * * The <OpenLayers.Control.type> of a control determines the behavior when * clicking its icon: * <OpenLayers.Control.TYPE_TOOL> - The control is activated and other * controls of this type in the same panel are deactivated. This is * the default type. * <OpenLayers.Control.TYPE_TOGGLE> - The active state of the control is * toggled. * <OpenLayers.Control.TYPE_BUTTON> - The * <OpenLayers.Control.Button.trigger> method of the control is called, * but its active state is not changed. * * If a control is <OpenLayers.Control.active>, it will be drawn with the * olControl[Name]ItemActive class, otherwise with the * olControl[Name]ItemInactive class. * * Parameters: * options - {Object} An optional object whose properties will be used * to extend the control. */ initialize: function(options) { OpenLayers.Control.prototype.initialize.apply(this, [options]); this.controls = []; this.activeState = {}; }, /** * APIMethod: destroy */ destroy: function() { OpenLayers.Control.prototype.destroy.apply(this, arguments); for(var i = this.controls.length - 1 ; i >= 0; i--) { if(this.controls[i].events) { this.controls[i].events.un({ "activate": this.redraw, "deactivate": this.redraw, scope: this }); } OpenLayers.Event.stopObservingElement(this.controls[i].panel_div); this.controls[i].panel_div = null; } this.activeState = null; }, /** * APIMethod: activate */ activate: function() { if (OpenLayers.Control.prototype.activate.apply(this, arguments)) { var control; for (var i=0, len=this.controls.length; i<len; i++) { control = this.controls[i]; if (control === this.defaultControl || (this.saveState && this.activeState[control.id])) { control.activate(); } } if (this.saveState === true) { this.defaultControl = null; } this.redraw(); return true; } else { return false; } }, /** * APIMethod: deactivate */ deactivate: function() { if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) { var control; for (var i=0, len=this.controls.length; i<len; i++) { control = this.controls[i]; this.activeState[control.id] = control.deactivate(); } return true; } else { return false; } }, /** * Method: draw * * Returns: * {DOMElement} */ draw: function() { OpenLayers.Control.prototype.draw.apply(this, arguments); this.addControlsToMap(this.controls); return this.div; }, /** * Method: redraw */ redraw: function() { if (this.div.children.length>0) { for (var l=this.div.children.length, i=l-1 ; i>=0 ; i--) { this.div.removeChild(this.div.children[i]); } } this.div.innerHTML = ""; if (this.active) { for (var i=0, len=this.controls.length; i<len; i++) { var element = this.controls[i].panel_div; if (this.controls[i].active) { element.className = this.controls[i].displayClass + "ItemActive"; } else { element.className = this.controls[i].displayClass + "ItemInactive"; } this.div.appendChild(element); } } }, /** * APIMethod: activateControl * This method is called when the user click on the icon representing a * control in the panel. * * Parameters: * control - {<OpenLayers.Control>} */ activateControl: function (control) { if (!this.active) { return false; } if (control.type == OpenLayers.Control.TYPE_BUTTON) { control.trigger(); this.redraw(); return; } if (control.type == OpenLayers.Control.TYPE_TOGGLE) { if (control.active) { control.deactivate(); } else { control.activate(); } this.redraw(); return; } var c; for (var i=0, len=this.controls.length; i<len; i++) { c = this.controls[i]; if (c != control && (c.type === OpenLayers.Control.TYPE_TOOL || c.type == null)) { c.deactivate(); } } control.activate(); }, /** * APIMethod: addControls * To build a toolbar, you add a set of controls to it. addControls * lets you add a single control or a list of controls to the * Control Panel. * * Parameters: * controls - {<OpenLayers.Control>} Controls to add in the panel. */ addControls: function(controls) { if (!(controls instanceof Array)) { controls = [controls]; } this.controls = this.controls.concat(controls); // Give each control a panel_div which will be used later. // Access to this div is via the panel_div attribute of the // control added to the panel. // Also, stop mousedowns and clicks, but don't stop mouseup, // since they need to pass through. for (var i=0, len=controls.length; i<len; i++) { var element = document.createElement("div"); controls[i].panel_div = element; if (controls[i].title != "") { controls[i].panel_div.title = controls[i].title; } OpenLayers.Event.observe(controls[i].panel_div, "click", OpenLayers.Function.bind(this.onClick, this, controls[i])); OpenLayers.Event.observe(controls[i].panel_div, "dblclick", OpenLayers.Function.bind(this.onDoubleClick, this, controls[i])); OpenLayers.Event.observe(controls[i].panel_div, "mousedown", OpenLayers.Function.bindAsEventListener(OpenLayers.Event.stop)); } if (this.map) { // map.addControl() has already been called on the panel this.addControlsToMap(controls); this.redraw(); } }, /** * Method: addControlsToMap * Only for internal use in draw() and addControls() methods. * * Parameters: * controls - {Array(<OpenLayers.Control>)} Controls to add into map. */ addControlsToMap: function (controls) { var control; for (var i=0, len=controls.length; i<len; i++) { control = controls[i]; if (control.autoActivate === true) { control.autoActivate = false; this.map.addControl(control); control.autoActivate = true; } else { this.map.addControl(control); control.deactivate(); } control.events.on({ "activate": this.redraw, "deactivate": this.redraw, scope: this }); } }, /** * Method: onClick */ onClick: function (ctrl, evt) { OpenLayers.Event.stop(evt ? evt : window.event); this.activateControl(ctrl); }, /** * Method: onDoubleClick */ onDoubleClick: function(ctrl, evt) { OpenLayers.Event.stop(evt ? evt : window.event); }, /** * APIMethod: getControlsBy * Get a list of controls with properties matching the given criteria. * * Parameter: * property - {String} A control property to be matched. * match - {String | Object} A string to match. Can also be a regular * expression literal or object. In addition, it can be any object * with a method named test. For reqular expressions or other, if * match.test(control[property]) evaluates to true, the control will be * included in the array returned. If no controls are found, an empty * array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given criteria. * An empty array is returned if no matches are found. */ getControlsBy: function(property, match) { var test = (typeof match.test == "function"); var found = OpenLayers.Array.filter(this.controls, function(item) { return item[property] == match || (test && match.test(item[property])); }); return found; }, /** * APIMethod: getControlsByName * Get a list of contorls with names matching the given name. * * Parameter: * match - {String | Object} A control name. The name can also be a regular * expression literal or object. In addition, it can be any object * with a method named test. For reqular expressions or other, if * name.test(control.name) evaluates to true, the control will be included * in the list of controls returned. If no controls are found, an empty * array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given name. * An empty array is returned if no matches are found. */ getControlsByName: function(match) { return this.getControlsBy("name", match); }, /** * APIMethod: getControlsByClass * Get a list of controls of a given type (CLASS_NAME). * * Parameter: * match - {String | Object} A control class name. The type can also be a * regular expression literal or object. In addition, it can be any * object with a method named test. For reqular expressions or other, * if type.test(control.CLASS_NAME) evaluates to true, the control will * be included in the list of controls returned. If no controls are * found, an empty array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given type. * An empty array is returned if no matches are found. */ getControlsByClass: function(match) { return this.getControlsBy("CLASS_NAME", match); }, CLASS_NAME: "OpenLayers.Control.Panel" });
cpat-client/src/components/target-types/location/forms/LocationCreate.js
meddlin/CPAT
import React from 'react'; import { useHistory } from 'react-router-dom'; import { connect } from 'react-redux'; import { withFormik, Form, FieldArray } from 'formik'; import * as Yup from 'yup'; import { Button, TextInput, Heading } from 'evergreen-ui'; import { LocationDocumentRelationFormArray } from './form-arrays/LocationDocumentRelationFormArray'; import styled from 'styled-components'; import { locationActions } from '../../../../state-management/location/actions'; import Location from '../../../../data/Location'; const FormStyle = styled.div` padding: 3em; form { display: flex; flex-direction: column; } `; const LocationCreate = (props) => { const { values, touched, errors, dirty, handleChange, handleBlur, handleSubmit, handleReset, isSubmitting, } = props; let history = useHistory(); return ( <div> <h2>Location: Create New</h2> <FormStyle> <Form> <label>Name</label> <TextInput name="name" label="Name" onChange={handleChange} onBlur={handleBlur} value={values.name} /> {(touched.name && errors.name) ? <div>{errors.name}</div> : ""} <label>Latitude</label> <TextInput name="latitude" label="Latitude" onChange={handleChange} onBlur={handleBlur} value={values.latitude} /> {(touched.latitude && errors.latitude) ? <div>{errors.latitude}</div> : ""} <label>Longitude</label> <TextInput name="longitude" label="Longitude" onChange={handleChange} onBlur={handleBlur} value={values.longitude} /> {(touched.longitude && errors.longitude) ? <div>{errors.longitude}</div> : ""} <FieldArray name="documentRelation" component={LocationDocumentRelationFormArray} /> <label>Date Created:</label> <TextInput disabled name="dateCreated" label="Date Created" value={`${new Date('2020-01-30').toLocaleDateString()}`} /> <label>Updated At:</label> <TextInput disabled name="updatedAt" label="Updated At" value={`${new Date().toLocaleDateString()}`} /> <label>Last Modified By:</label> <TextInput disabled name="lastModifiedBy" label="Last Modified By" value={`You - User 1`} /> <Button type="submit">Create</Button> <Button onClick={handleReset}>Cancel</Button> </Form> <Button onClick={() => history.goBack()}>Back</Button> </FormStyle> </div> ) }; const formikEnhancer = withFormik({ mapPropsToValues: ({ name, latitude, longitude, documentRelation, dateCreated, updatedAt, lastModifiedBy }) => { return { name: name || '', latitude: latitude || '', longitude: longitude || '', documentRelation: documentRelation || [{}], dateCreated: dateCreated, updatedAt: updatedAt, lastModifiedBy: lastModifiedBy } }, validationSchema: Yup.object().shape({ name: Yup.string().required('Name is required') }), handleSubmit: (values, { props, setSubmitting }) => { let newLocation = new Location(); newLocation.name = values.name || ''; newLocation.latitude = values.latitude || ''; newLocation.longitude = values.longitude || ''; newLocation.documentRelation = values.documentRelation || [{}]; newLocation.dateCreated = values.dateCreated || new Date(); newLocation.updatedAt = values.updatedAt || new Date(); newLocation.lastModifiedBy = values.lastModifiedBy; props.dispatch(locationActions.insertLocation(newLocation.apiObject())); setSubmitting(false); } })(LocationCreate); function mapStateToProps(state) { const { } = state; return { }; } const LocationCreateConnection = connect(mapStateToProps)(formikEnhancer); export { LocationCreateConnection as LocationCreate };
native/ChatItem/ChatItem.js
abdurrahmanekr/react-chat-elements
import React, { Component } from 'react'; import styles from './ChatItemStyle.js'; import Avatar from '../Avatar/Avatar'; import { View, Text, Image, } from 'react-native'; export class ChatItem extends Component { render() { return ( <View style={styles.rceContainerCitem} onClick={this.props.onClick} onContextMenu={this.props.onContextMenu}> <View style={styles.rceCitem}> <View style={styles.rceCitemAvatar}> <Avatar src={this.props.avatar} alt={this.props.alt} sideElement={ this.props.statusColor && <View style={[styles.rceCitemStatus, {backgroundColor: this.props.statusColor}]}> <Text> {this.props.statusText} </Text> </View> } type={'circle' && {'flexible': this.props.avatarFlexible}}/> </View> <View style={styles.rceCitemBody}> <View style={styles.rceCitemBodyTop}> <Text ellipsizeMode='tail' numberOfLines={1} style={styles.rceCitemBodyTopTitle}> {this.props.title} </Text> <Text style={styles.rceCitemBodyTopTime} ellipsizeMode='tail' numberOfLines={1}> { this.props.date && !isNaN(this.props.date) && ( this.props.dateString || (this.props.date).toString() ) } </Text> </View> <View style={styles.rceCitemBodyBottom}> <Text ellipsizeMode='tail' numberOfLines={1} style={styles.rceCitemBodyTopTitle}> {this.props.subtitle} </Text> { this.props.unread > 0 && <View style={styles.rceCitemBodyBottomStatus}> <Text style={styles.rceCitemBodyBottomStatusText}> {this.props.unread} </Text> </View> } </View> </View> </View> </View> ); } } ChatItem.defaultProps = { id: '', onClick: null, avatar: '', avatarFlexible: false, alt: '', title: '', subtitle: '', date: new Date(), unread: 0, statusColor: null, statusText: null, dateString: null, } export default ChatItem;
addons/info/example/story.js
bigassdragon/storybook
import React from 'react'; import Button from './Button'; import { storiesOf, action } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import backgrounds from 'react-storybook-addon-backgrounds'; storiesOf( 'Button', ).addWithInfo( 'simple usage', 'This is the basic usage with the button with providing a label to show the text.', () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> <p> Click the "?" mark at top-right to view the info. </p> </div> ), ); storiesOf('Button').addWithInfo( 'simple usage (inline info)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true }, ); storiesOf('Button').addWithInfo( 'simple usage (disable source)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { source: false, inline: true }, ); storiesOf('Button').addWithInfo( 'simple usage (no header)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { header: false, inline: true }, ); storiesOf('Button').addWithInfo( 'simple usage (no prop tables)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { propTables: false, inline: true }, ); storiesOf('Button').addWithInfo( 'simple usage (custom propTables)', ` This is the basic usage with the button with providing a label to show the text. Since, the story source code is wrapped inside a div, info addon can't figure out propTypes on it's own. So, we need to give relevant React component classes manually using \`propTypes\` option as shown below: ~~~js storiesOf('Button') .addWithInfo( 'simple usage (custom propTables)', <info>, <storyFn>, { inline: true, propTables: [Button]} ); ~~~ `, () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> </div> ), { inline: true, propTables: [Button] }, ); storiesOf('Button').addWithInfo( 'simple usage (JSX description)', <div> <h2>This is a JSX info section</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare massa rutrum metus commodo, a mattis velit dignissim. Fusce vestibulum turpis sed massa egestas pharetra. Sed at libero nulla. </p> <p> <a href="https://github.com/storybooks/react-storybook-addon-info"> This is a link </a> </p> <p> <img src="http://placehold.it/350x150" /> </p> </div>, () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> <p> Click the "?" mark at top-right to view the info. </p> </div> ), ); storiesOf('Button').addWithInfo( 'simple usage (inline JSX description)', <div> <h2>This is a JSX info section</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare massa rutrum metus commodo, a mattis velit dignissim. Fusce vestibulum turpis sed massa egestas pharetra. Sed at libero nulla. </p> <p> <a href="https://github.com/storybooks/react-storybook-addon-info"> This is a link </a> </p> <p> <img src="http://placehold.it/350x150" /> </p> </div>, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true }, ); storiesOf('Button') .addDecorator(backgrounds([{ name: 'dark', value: '#333', default: true }])) .addWithInfo( 'with custom styles', ` This is an example of how to customize the styles of the info components. For the full styles available, see \`./src/components/Story.js\` `, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true, styles: stylesheet => { stylesheet.infoPage = { backgroundColor: '#ccc', }; return stylesheet; }, }, );
ajax/libs/oboe.js/1.10.2/oboe-browser.js
jackdoyle/cdnjs
// This file is the concatenation of many js files. // See https://github.com/jimhigson/oboe.js for the raw source (function (window, Object, Array, Error, undefined ) { /* Copyright (c) 2013, Jim Higson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Partially complete a function. * * Eg: * var add3 = partialComplete( function add(a,b){return a+b}, 3 ); * * add3(4) // gives 7 * * * function wrap(left, right, cen){return left + " " + cen + " " + right;} * * var pirateGreeting = partialComplete( wrap , "I'm", ", a mighty pirate!" ); * * pirateGreeting("Guybrush Threepwood"); * // gives "I'm Guybrush Threepwood, a mighty pirate!" */ var partialComplete = varArgs(function( fn, args ) { // this isn't the shortest way to write this but it does // avoid creating a new array each time to pass to fn.apply, // otherwise could just call boundArgs.concat(callArgs) var numBoundArgs = args.length; return varArgs(function( callArgs ) { for (var i = 0; i < callArgs.length; i++) { args[numBoundArgs + i] = callArgs[i]; } args.length = numBoundArgs + callArgs.length; return fn.apply(this, args); }); }), /** * Compose zero or more functions: * * compose(f1, f2, f3)(x) = f1(f2(f3(x)))) * * The last (inner-most) function may take more than one parameter: * * compose(f1, f2, f3)(x,y) = f1(f2(f3(x,y)))) */ compose = varArgs(function(fns) { var fnsList = arrayAsList(fns); function next(params, curFn) { return [apply(params, curFn)]; } return varArgs(function(startParams){ return foldR(next, startParams, fnsList)[0]; }); }); /** * A more optimised version of compose that takes exactly two functions * @param f1 * @param f2 */ function compose2(f1, f2){ return function(){ return f1.call(this,f2.apply(this,arguments)); } } /** * Generic form for a function to get a property from an object * * var o = { * foo:'bar' * } * * var getFoo = attr('foo') * * fetFoo(o) // returns 'bar' * * @param {String} key the property name */ function attr(key) { return new Function('o', 'return o["' + key + '"]' ); } /** * Call a list of functions with the same args until one returns a * truthy result. Similar to the || operator. * * So: * lazyUnion([f1,f2,f3 ... fn])( p1, p2 ... pn ) * * Is equivalent to: * apply([p1, p2 ... pn], f1) || * apply([p1, p2 ... pn], f2) || * apply([p1, p2 ... pn], f3) ... apply(fn, [p1, p2 ... pn]) * * @returns the first return value that is given that is truthy. */ lazyUnion = varArgs(function(fns) { return varArgs(function(params){ var maybeValue; for (var i = 0; i < len(fns); i++) { maybeValue = apply(params, fns[i]); if( maybeValue ) { return maybeValue; } } }); }); /** * This file declares various pieces of functional programming. * * This isn't a general purpose functional library, to keep things small it * has just the parts useful for Oboe.js. */ /** * Call a single function with the given arguments array. * Basically, a functional-style version of the OO-style Function#apply for * when we don't care about the context ('this') of the call. * * The order of arguments allows partial completion of the arguments array */ function apply(args, fn) { return fn.apply(undefined, args); } /** * Define variable argument functions but cut out all that tedious messing about * with the arguments object. Delivers the variable-length part of the arguments * list as an array. * * Eg: * * var myFunction = varArgs( * function( fixedArgument, otherFixedArgument, variableNumberOfArguments ){ * console.log( variableNumberOfArguments ); * } * ) * * myFunction('a', 'b', 1, 2, 3); // logs [1,2,3] * * var myOtherFunction = varArgs(function( variableNumberOfArguments ){ * console.log( variableNumberOfArguments ); * }) * * myFunction(1, 2, 3); // logs [1,2,3] * */ function varArgs(fn){ var numberOfFixedArguments = fn.length -1, slice = Array.prototype.slice; if( numberOfFixedArguments == 0 ) { // an optimised case for when there are no fixed args: return function(){ return fn.call(this, slice.call(arguments)); } } else if( numberOfFixedArguments == 1 ) { // an optimised case for when there are is one fixed args: return function(){ return fn.call(this, arguments[0], slice.call(arguments, 1)); } } // general case // we know how many arguments fn will always take. Create a // fixed-size array to hold that many, to be re-used on // every call to the returned function var argsHolder = Array(fn.length); return function(){ for (var i = 0; i < numberOfFixedArguments; i++) { argsHolder[i] = arguments[i]; } argsHolder[numberOfFixedArguments] = slice.call(arguments, numberOfFixedArguments); return fn.apply( this, argsHolder); } } /** * Swap the order of parameters to a binary function * * A bit like this flip: http://zvon.org/other/haskell/Outputprelude/flip_f.html */ function flip(fn){ return function(a, b){ return fn(b,a); } } /** * Create a function which is the intersection of two other functions. * * Like the && operator, if the first is truthy, the second is never called, * otherwise the return value from the second is returned. */ function lazyIntersection(fn1, fn2) { return function (param) { return fn1(param) && fn2(param); }; } /** * A function which does nothing */ function noop(){} /** * A function which is always happy */ function always(){return true} /** * Create a function which always returns the same * value * * var return3 = functor(3); * * return3() // gives 3 * return3() // still gives 3 * return3() // will always give 3 */ function functor(val){ return function(){ return val; } } /** * This file defines some loosely associated syntactic sugar for * Javascript programming */ /** * Returns true if the given candidate is of type T */ function isOfType(T, maybeSomething){ return maybeSomething && maybeSomething.constructor === T; } var len = attr('length'), isString = partialComplete(isOfType, String); /** * I don't like saying this: * * foo !=== undefined * * because of the double-negative. I find this: * * defined(foo) * * easier to read. */ function defined( value ) { return value !== undefined; } /** * Returns true if object o has a key named like every property in * the properties array. Will give false if any are missing, or if o * is not an object. */ function hasAllProperties(fieldList, o) { return (o instanceof Object) && all(function (field) { return (field in o); }, fieldList); } /** * Like cons in Lisp */ function cons(x, xs) { /* Internally lists are linked 2-element Javascript arrays. So that lists are all immutable we Object.freeze in newer Javascript runtimes. In older engines freeze should have been polyfilled as the identity function. */ return Object.freeze([x,xs]); } /** * The empty list */ var emptyList = null, /** * Get the head of a list. * * Ie, head(cons(a,b)) = a */ head = attr(0), /** * Get the tail of a list. * * Ie, head(cons(a,b)) = a */ tail = attr(1); /** * Converts an array to a list * * asList([a,b,c]) * * is equivalent to: * * cons(a, cons(b, cons(c, emptyList))) **/ function arrayAsList(inputArray){ return reverseList( inputArray.reduce( flip(cons), emptyList ) ); } /** * A varargs version of arrayAsList. Works a bit like list * in LISP. * * list(a,b,c) * * is equivalent to: * * cons(a, cons(b, cons(c, emptyList))) */ var list = varArgs(arrayAsList); /** * Convert a list back to a js native array */ function listAsArray(list){ return foldR( function(arraySoFar, listItem){ arraySoFar.unshift(listItem); return arraySoFar; }, [], list ); } /** * Map a function over a list */ function map(fn, list) { return list ? cons(fn(head(list)), map(fn,tail(list))) : emptyList ; } /** * foldR implementation. Reduce a list down to a single value. * * @pram {Function} fn (rightEval, curVal) -> result */ function foldR(fn, startValue, list) { return list ? fn(foldR(fn, startValue, tail(list)), head(list)) : startValue ; } /** * foldR implementation. Reduce a list down to a single value. * * @pram {Function} fn (rightEval, curVal) -> result */ function foldR1(fn, list) { return tail(list) ? fn(foldR1(fn, tail(list)), head(list)) : head(list) ; } /** * Return a list like the one given but with the first instance equal * to item removed */ function without(list, test, removedFn) { return withoutInner(list, removedFn || noop); function withoutInner(subList, removedFn) { return subList ? ( test(head(subList)) ? (removedFn(head(subList)), tail(subList)) : cons(head(subList), withoutInner(tail(subList), removedFn)) ) : emptyList ; } } /** * Returns true if the given function holds for every item in * the list, false otherwise */ function all(fn, list) { return !list || ( fn(head(list)) && all(fn, tail(list)) ); } /** * Call every function in a list of functions with the same arguments * * This doesn't make any sense if we're doing pure functional because * it doesn't return anything. Hence, this is only really useful if the * functions being called have side-effects. */ function applyEach(fnList, arguments) { if( fnList ) { head(fnList).apply(null, arguments); applyEach(tail(fnList), arguments); } } /** * Reverse the order of a list */ function reverseList(list){ // js re-implementation of 3rd solution from: // http://www.haskell.org/haskellwiki/99_questions/Solutions/5 function reverseInner( list, reversedAlready ) { if( !list ) { return reversedAlready; } return reverseInner(tail(list), cons(head(list), reversedAlready)) } return reverseInner(list, emptyList); } function first(test, list) { return list && (test(head(list)) ? head(list) : first(test,tail(list))); } /* This is a slightly hacked-up browser only version of clarinet with some features removed to help keep Oboe under the 5k micro-library limit For the original go here: https://github.com/dscape/clarinet */ var clarinet = (function () { var clarinet = {} , fastlist = Array ; clarinet.parser = function () { return new CParser();}; clarinet.CParser = CParser; clarinet.MAX_BUFFER_LENGTH = 64 * 1024; clarinet.EVENTS = [ "value" , "string" , "key" , "openobject" , "closeobject" , "openarray" , "closearray" , "error" , "end" , "ready" ]; var buffers = [ "textNode", "numberNode" ] , _n = 0 ; var BEGIN = _n++; var VALUE = _n++; // general stuff var OPEN_OBJECT = _n++; // { var CLOSE_OBJECT = _n++; // } var OPEN_ARRAY = _n++; // [ var CLOSE_ARRAY = _n++; // ] var STRING = _n++; // "" var OPEN_KEY = _n++; // , "a" var CLOSE_KEY = _n++; // : var TRUE = _n++; // r var TRUE2 = _n++; // u var TRUE3 = _n++; // e var FALSE = _n++; // a var FALSE2 = _n++; // l var FALSE3 = _n++; // s var FALSE4 = _n++; // e var NULL = _n++; // u var NULL2 = _n++; // l var NULL3 = _n++; // l var NUMBER_DECIMAL_POINT = _n++; // . var NUMBER_DIGIT = _n; // [0-9] if (!Object.create) { Object.create = function (o) { function f () { this["__proto__"] = o; } f.prototype = o; return new f; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function (o) { return o["__proto__"]; }; } if (!Object.keys) { Object.keys = function (o) { var a = []; for (var i in o) if (o.hasOwnProperty(i)) a.push(i); return a; }; } function checkBufferLength (parser) { var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10) , maxActual = 0 ; for (var i = 0, l = buffers.length; i < l; i ++) { var len = parser[buffers[i]].length; if (len > maxAllowed) { switch (buffers[i]) { case "text": closeText(parser); break; default: error(parser, "Max buffer length exceeded: "+ buffers[i]); } } maxActual = Math.max(maxActual, len); } parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual) + parser.position; } function clearBuffers (parser) { for (var i = 0, l = buffers.length; i < l; i ++) { parser[buffers[i]] = ""; } } var stringTokenPattern = /[\\"\n]/g; function CParser () { if (!(this instanceof CParser)) return new CParser (); var parser = this; clearBuffers(parser); parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH; parser.q = parser.c = parser.p = ""; parser.closed = parser.closedRoot = parser.sawRoot = false; parser.tag = parser.error = null; parser.state = BEGIN; parser.stack = new fastlist(); // mostly just for error reporting parser.position = parser.column = 0; parser.line = 1; parser.slashed = false; parser.unicodeI = 0; parser.unicodeS = null; emit(parser, "onready"); } CParser.prototype = { end : function () { end(this); } , write : write , close : function () { return this.write(null); } }; function emit(parser, event, data) { if (parser[event]) parser[event](data); } function emitNode(parser, event, data) { closeValue(parser); emit(parser, event, data); } function closeValue(parser, event) { if (parser.textNode) { emit(parser, (event ? event : "onvalue"), parser.textNode); } parser.textNode = ""; } function closeNumber(parser) { if (parser.numberNode) emit(parser, "onvalue", parseFloat(parser.numberNode)); parser.numberNode = ""; } function error (parser, er) { closeValue(parser); er += "\nLine: "+parser.line+ "\nColumn: "+parser.column+ "\nChar: "+parser.c; er = new Error(er); parser.error = er; emit(parser, "onerror", er); return parser; } function end(parser) { if (parser.state !== VALUE) error(parser, "Unexpected end"); closeValue(parser); parser.c = ""; parser.closed = true; emit(parser, "onend"); CParser.call(parser); return parser; } function write (chunk) { var parser = this; // this used to throw the error but inside Oboe we will have already // gotten the error when it was emitted. The important thing is to // not continue with the parse. if (this.error) return; if (parser.closed) return error(parser, "Cannot write after close. Assign an onready handler."); if (chunk === null) return end(parser); var i = 0, c = chunk[0], p = parser.p; while (c) { p = c; parser.c = c = chunk.charAt(i++); // if chunk doesnt have next, like streaming char by char // this way we need to check if previous is really previous // if not we need to reset to what the parser says is the previous // from buffer if(p !== c ) parser.p = p; else p = parser.p; if(!c) break; parser.position ++; if (c === "\n") { parser.line ++; parser.column = 0; } else parser.column ++; switch (parser.state) { case BEGIN: if (c === "{") parser.state = OPEN_OBJECT; else if (c === "[") parser.state = OPEN_ARRAY; else if (c !== '\r' && c !== '\n' && c !== ' ' && c !== '\t') error(parser, "Non-whitespace before {[."); continue; case OPEN_KEY: case OPEN_OBJECT: if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; if(parser.state === OPEN_KEY) parser.stack.push(CLOSE_KEY); else { if(c === '}') { emit(parser, 'onopenobject'); emit(parser, 'oncloseobject'); parser.state = parser.stack.pop() || VALUE; continue; } else parser.stack.push(CLOSE_OBJECT); } if(c === '"') parser.state = STRING; else error(parser, "Malformed object key should start with \""); continue; case CLOSE_KEY: case CLOSE_OBJECT: if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; if(c===':') { if(parser.state === CLOSE_OBJECT) { parser.stack.push(CLOSE_OBJECT); closeValue(parser, 'onopenobject'); } else closeValue(parser, 'onkey'); parser.state = VALUE; } else if (c==='}') { emitNode(parser, 'oncloseobject'); parser.state = parser.stack.pop() || VALUE; } else if(c===',') { if(parser.state === CLOSE_OBJECT) parser.stack.push(CLOSE_OBJECT); closeValue(parser); parser.state = OPEN_KEY; } else error(parser, 'Bad object'); continue; case OPEN_ARRAY: // after an array there always a value case VALUE: if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; if(parser.state===OPEN_ARRAY) { emit(parser, 'onopenarray'); parser.state = VALUE; if(c === ']') { emit(parser, 'onclosearray'); parser.state = parser.stack.pop() || VALUE; continue; } else { parser.stack.push(CLOSE_ARRAY); } } if(c === '"') parser.state = STRING; else if(c === '{') parser.state = OPEN_OBJECT; else if(c === '[') parser.state = OPEN_ARRAY; else if(c === 't') parser.state = TRUE; else if(c === 'f') parser.state = FALSE; else if(c === 'n') parser.state = NULL; else if(c === '-') { // keep and continue parser.numberNode += c; } else if(c==='0') { parser.numberNode += c; parser.state = NUMBER_DIGIT; } else if('123456789'.indexOf(c) !== -1) { parser.numberNode += c; parser.state = NUMBER_DIGIT; } else error(parser, "Bad value"); continue; case CLOSE_ARRAY: if(c===',') { parser.stack.push(CLOSE_ARRAY); closeValue(parser, 'onvalue'); parser.state = VALUE; } else if (c===']') { emitNode(parser, 'onclosearray'); parser.state = parser.stack.pop() || VALUE; } else if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; else error(parser, 'Bad array'); continue; case STRING: // thanks thejh, this is an about 50% performance improvement. var starti = i-1 , slashed = parser.slashed , unicodeI = parser.unicodeI ; STRING_BIGLOOP: while (true) { // zero means "no unicode active". 1-4 mean "parse some more". end after 4. while (unicodeI > 0) { parser.unicodeS += c; c = chunk.charAt(i++); if (unicodeI === 4) { // TODO this might be slow? well, probably not used too often anyway parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16)); unicodeI = 0; starti = i-1; } else { unicodeI++; } // we can just break here: no stuff we skipped that still has to be sliced out or so if (!c) break STRING_BIGLOOP; } if (c === '"' && !slashed) { parser.state = parser.stack.pop() || VALUE; parser.textNode += chunk.substring(starti, i-1); if(!parser.textNode) { emit(parser, "onvalue", ""); } break; } if (c === '\\' && !slashed) { slashed = true; parser.textNode += chunk.substring(starti, i-1); c = chunk.charAt(i++); if (!c) break; } if (slashed) { slashed = false; if (c === 'n') { parser.textNode += '\n'; } else if (c === 'r') { parser.textNode += '\r'; } else if (c === 't') { parser.textNode += '\t'; } else if (c === 'f') { parser.textNode += '\f'; } else if (c === 'b') { parser.textNode += '\b'; } else if (c === 'u') { // \uxxxx. meh! unicodeI = 1; parser.unicodeS = ''; } else { parser.textNode += c; } c = chunk.charAt(i++); starti = i-1; if (!c) break; else continue; } stringTokenPattern.lastIndex = i; var reResult = stringTokenPattern.exec(chunk); if (reResult === null) { i = chunk.length+1; parser.textNode += chunk.substring(starti, i-1); break; } i = reResult.index+1; c = chunk.charAt(reResult.index); if (!c) { parser.textNode += chunk.substring(starti, i-1); break; } } parser.slashed = slashed; parser.unicodeI = unicodeI; continue; case TRUE: if (c==='') continue; // strange buffers if (c==='r') parser.state = TRUE2; else error(parser, 'Invalid true started with t'+ c); continue; case TRUE2: if (c==='') continue; if (c==='u') parser.state = TRUE3; else error(parser, 'Invalid true started with tr'+ c); continue; case TRUE3: if (c==='') continue; if(c==='e') { emit(parser, "onvalue", true); parser.state = parser.stack.pop() || VALUE; } else error(parser, 'Invalid true started with tru'+ c); continue; case FALSE: if (c==='') continue; if (c==='a') parser.state = FALSE2; else error(parser, 'Invalid false started with f'+ c); continue; case FALSE2: if (c==='') continue; if (c==='l') parser.state = FALSE3; else error(parser, 'Invalid false started with fa'+ c); continue; case FALSE3: if (c==='') continue; if (c==='s') parser.state = FALSE4; else error(parser, 'Invalid false started with fal'+ c); continue; case FALSE4: if (c==='') continue; if (c==='e') { emit(parser, "onvalue", false); parser.state = parser.stack.pop() || VALUE; } else error(parser, 'Invalid false started with fals'+ c); continue; case NULL: if (c==='') continue; if (c==='u') parser.state = NULL2; else error(parser, 'Invalid null started with n'+ c); continue; case NULL2: if (c==='') continue; if (c==='l') parser.state = NULL3; else error(parser, 'Invalid null started with nu'+ c); continue; case NULL3: if (c==='') continue; if(c==='l') { emit(parser, "onvalue", null); parser.state = parser.stack.pop() || VALUE; } else error(parser, 'Invalid null started with nul'+ c); continue; case NUMBER_DECIMAL_POINT: if(c==='.') { parser.numberNode += c; parser.state = NUMBER_DIGIT; } else error(parser, 'Leading zero not followed by .'); continue; case NUMBER_DIGIT: if('0123456789'.indexOf(c) !== -1) parser.numberNode += c; else if (c==='.') { if(parser.numberNode.indexOf('.')!==-1) error(parser, 'Invalid number has two dots'); parser.numberNode += c; } else if (c==='e' || c==='E') { if(parser.numberNode.indexOf('e')!==-1 || parser.numberNode.indexOf('E')!==-1 ) error(parser, 'Invalid number has two exponential'); parser.numberNode += c; } else if (c==="+" || c==="-") { if(!(p==='e' || p==='E')) error(parser, 'Invalid symbol in number'); parser.numberNode += c; } else { closeNumber(parser); i--; // go back one parser.state = parser.stack.pop() || VALUE; } continue; default: error(parser, "Unknown state: " + parser.state); } } if (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser); return parser; } return clarinet; })(); /** * A bridge used to assign stateless functions to listen to clarinet. * * As well as the parameter from clarinet, each callback will also be passed * the result of the last callback. * * This may also be used to clear all listeners by assigning zero handlers: * * clarinetListenerAdaptor( clarinet, {} ) */ function clarinetListenerAdaptor(clarinetParser, handlers){ var state; clarinet.EVENTS.forEach(function(eventName){ var handlerFunction = handlers[eventName]; clarinetParser['on'+eventName] = handlerFunction && function(param) { state = handlerFunction( state, param); }; }); } // based on gist https://gist.github.com/monsur/706839 /** * XmlHttpRequest's getAllResponseHeaders() method returns a string of response * headers according to the format described here: * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method * This method parses that string into a user-friendly key/value pair object. */ function parseResponseHeaders(headerStr) { var headers = {}; headerStr && headerStr.split('\u000d\u000a') .forEach(function(headerPair){ // Can't use split() here because it does the wrong thing // if the header value has the string ": " in it. var index = headerPair.indexOf('\u003a\u0020'); headers[headerPair.substring(0, index)] = headerPair.substring(index + 2); }); return headers; } function httpTransport(){ return new XMLHttpRequest(); } /** * A wrapper around the browser XmlHttpRequest object that raises an * event whenever a new part of the response is available. * * In older browsers progressive reading is impossible so all the * content is given in a single call. For newer ones several events * should be raised, allowing progressive interpretation of the response. * * @param {Function} oboeBus an event bus local to this Oboe instance * @param {XMLHttpRequest} xhr the xhr to use as the transport. Under normal * operation, will have been created using httpTransport() above * but for tests a stub can be provided instead. * @param {String} method one of 'GET' 'POST' 'PUT' 'PATCH' 'DELETE' * @param {String} url the url to make a request to * @param {String|Object} data some content to be sent with the request. * Only valid if method is POST or PUT. * @param {Object} [headers] the http request headers to send */ function streamingHttp(oboeBus, xhr, method, url, data, headers) { var emitStreamData = oboeBus(STREAM_DATA).emit, emitFail = oboeBus(FAIL_EVENT).emit, numberOfCharsAlreadyGivenToCallback = 0; // When an ABORTING message is put on the event bus abort // the ajax request oboeBus( ABORTING ).on( function(){ // if we keep the onreadystatechange while aborting the XHR gives // a callback like a successful call so first remove this listener // by assigning null: xhr.onreadystatechange = null; xhr.abort(); }); /** Given a value from the user to send as the request body, return in * a form that is suitable to sending over the wire. Returns either a * string, or null. */ function validatedRequestBody( body ) { if( !body ) return null; return isString(body)? body: JSON.stringify(body); } /** * Handle input from the underlying xhr: either a state change, * the progress event or the request being complete. */ function handleProgress() { var textSoFar = xhr.responseText, newText = textSoFar.substr(numberOfCharsAlreadyGivenToCallback); /* Raise the event for new text. On older browsers, the new text is the whole response. On newer/better ones, the fragment part that we got since last progress. */ if( newText ) { emitStreamData( newText ); } numberOfCharsAlreadyGivenToCallback = len(textSoFar); } if('onprogress' in xhr){ // detect browser support for progressive delivery xhr.onprogress = handleProgress; } xhr.onreadystatechange = function() { switch( xhr.readyState ) { case 2: oboeBus( HTTP_START ).emit( xhr.status, parseResponseHeaders(xhr.getAllResponseHeaders()) ); return; case 4: // is this a 2xx http code? var sucessful = String(xhr.status)[0] == 2; if( sucessful ) { // In Chrome 29 (not 28) no onprogress is emitted when a response // is complete before the onload. We need to always do handleInput // in case we get the load but have not had a final progress event. // This looks like a bug and may change in future but let's take // the safest approach and assume we might not have received a // progress event for each part of the response handleProgress(); oboeBus(STREAM_END).emit(); } else { emitFail( errorReport( xhr.status, xhr.responseText )); } } }; try{ xhr.open(method, url, true); for( var headerName in headers ){ xhr.setRequestHeader(headerName, headers[headerName]); } xhr.send(validatedRequestBody(data)); } catch( e ) { // To keep a consistent interface with Node, we can't emit an event here. // Node's streaming http adaptor receives the error as an asynchronous // event rather than as an exception. If we emitted now, the Oboe user // has had no chance to add a .fail listener so there is no way // the event could be useful. For both these reasons defer the // firing to the next JS frame. window.setTimeout( partialComplete(emitFail, errorReport(undefined, undefined, e)) , 0 ); } } var jsonPathSyntax = (function() { var /** * Export a regular expression as a simple function by exposing just * the Regex#exec. This allows regex tests to be used under the same * interface as differently implemented tests, or for a user of the * tests to not concern themselves with their implementation as regular * expressions. * * This could also be expressed point-free as: * Function.prototype.bind.bind(RegExp.prototype.exec), * * But that's far too confusing! (and not even smaller once minified * and gzipped) */ regexDescriptor = function regexDescriptor(regex) { return regex.exec.bind(regex); } /** * Join several regular expressions and express as a function. * This allows the token patterns to reuse component regular expressions * instead of being expressed in full using huge and confusing regular * expressions. */ , jsonPathClause = varArgs(function( componentRegexes ) { // The regular expressions all start with ^ because we // only want to find matches at the start of the // JSONPath fragment we are inspecting componentRegexes.unshift(/^/); return regexDescriptor( RegExp( componentRegexes.map(attr('source')).join('') ) ); }) , possiblyCapturing = /(\$?)/ , namedNode = /([\w-_]+|\*)/ , namePlaceholder = /()/ , nodeInArrayNotation = /\["([^"]+)"\]/ , numberedNodeInArrayNotation = /\[(\d+|\*)\]/ , fieldList = /{([\w ]*?)}/ , optionalFieldList = /(?:{([\w ]*?)})?/ // foo or * , jsonPathNamedNodeInObjectNotation = jsonPathClause( possiblyCapturing, namedNode, optionalFieldList ) // ["foo"] , jsonPathNamedNodeInArrayNotation = jsonPathClause( possiblyCapturing, nodeInArrayNotation, optionalFieldList ) // [2] or [*] , jsonPathNumberedNodeInArrayNotation = jsonPathClause( possiblyCapturing, numberedNodeInArrayNotation, optionalFieldList ) // {a b c} , jsonPathPureDuckTyping = jsonPathClause( possiblyCapturing, namePlaceholder, fieldList ) // .. , jsonPathDoubleDot = jsonPathClause(/\.\./) // . , jsonPathDot = jsonPathClause(/\./) // ! , jsonPathBang = jsonPathClause( possiblyCapturing, /!/ ) // nada! , emptyString = jsonPathClause(/$/) ; /* We export only a single function. When called, this function injects into another function the descriptors from above. */ return function (fn){ return fn( lazyUnion( jsonPathNamedNodeInObjectNotation , jsonPathNamedNodeInArrayNotation , jsonPathNumberedNodeInArrayNotation , jsonPathPureDuckTyping ) , jsonPathDoubleDot , jsonPathDot , jsonPathBang , emptyString ); }; }()); /** * Get a new key->node mapping * * @param {String|Number} key * @param {Object|Array|String|Number|null} node a value found in the json */ function namedNode(key, node) { return {key:key, node:node}; } /** get the key of a namedNode */ var keyOf = attr('key'); /** get the node from a namedNode */ var nodeOf = attr('node'); /** * This file provides various listeners which can be used to build up * a changing ascent based on the callbacks provided by Clarinet. It listens * to the low-level events from Clarinet and emits higher-level ones. * * The building up is stateless so to track a JSON file * clarinetListenerAdaptor.js is required to store the ascent state * between calls. */ /** * A special value to use in the path list to represent the path 'to' a root * object (which doesn't really have any path). This prevents the need for * special-casing detection of the root object and allows it to be treated * like any other object. We might think of this as being similar to the * 'unnamed root' domain ".", eg if I go to * http://en.wikipedia.org./wiki/En/Main_page the dot after 'org' deliminates * the unnamed root of the DNS. * * This is kept as an object to take advantage that in Javascript's OO objects * are guaranteed to be distinct, therefore no other object can possibly clash * with this one. Strings, numbers etc provide no such guarantee. **/ var ROOT_PATH = {}; /** * Create a new set of handlers for clarinet's events, bound to the emit * function given. */ function incrementalContentBuilder( oboeBus ) { var emitNodeFound = oboeBus(NODE_FOUND).emit, emitRootFound = oboeBus(ROOT_FOUND).emit, emitPathFound = oboeBus(PATH_FOUND).emit; function arrayIndicesAreKeys( possiblyInconsistentAscent, newDeepestNode) { /* for values in arrays we aren't pre-warned of the coming paths (Clarinet gives no call to onkey like it does for values in objects) so if we are in an array we need to create this path ourselves. The key will be len(parentNode) because array keys are always sequential numbers. */ var parentNode = nodeOf( head( possiblyInconsistentAscent)); return isOfType( Array, parentNode) ? pathFound( possiblyInconsistentAscent, len(parentNode), newDeepestNode ) : // nothing needed, return unchanged possiblyInconsistentAscent ; } function nodeFound( ascent, newDeepestNode ) { if( !ascent ) { // we discovered the root node, emitRootFound( newDeepestNode); return pathFound( ascent, ROOT_PATH, newDeepestNode); } // we discovered a non-root node var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode), ancestorBranches = tail( arrayConsistentAscent), previouslyUnmappedName = keyOf( head( arrayConsistentAscent)); appendBuiltContent( ancestorBranches, previouslyUnmappedName, newDeepestNode ); return cons( namedNode( previouslyUnmappedName, newDeepestNode ), ancestorBranches ); } /** * Add a new value to the object we are building up to represent the * parsed JSON */ function appendBuiltContent( ancestorBranches, key, node ){ nodeOf( head( ancestorBranches))[key] = node; } /** * For when we find a new key in the json. * * @param {String|Number|Object} newDeepestName the key. If we are in an * array will be a number, otherwise a string. May take the special * value ROOT_PATH if the root node has just been found * * @param {String|Number|Object|Array|Null|undefined} [maybeNewDeepestNode] * usually this won't be known so can be undefined. Can't use null * to represent unknown because null is a valid value in JSON **/ function pathFound(ascent, newDeepestName, maybeNewDeepestNode) { if( ascent ) { // if not root // If we have the key but (unless adding to an array) no known value // yet. Put that key in the output but against no defined value: appendBuiltContent( ascent, newDeepestName, maybeNewDeepestNode ); } var ascentWithNewPath = cons( namedNode( newDeepestName, maybeNewDeepestNode), ascent ); emitPathFound( ascentWithNewPath); return ascentWithNewPath; } /** * For when the current node ends */ function nodeFinished( ascent ) { emitNodeFound( ascent); // pop the complete node and its path off the list: return tail( ascent); } return { openobject : function (ascent, firstKey) { var ascentAfterNodeFound = nodeFound(ascent, {}); /* It is a perculiarity of Clarinet that for non-empty objects it gives the first key with the openobject event instead of in a subsequent key event. firstKey could be the empty string in a JSON object like {'':'foo'} which is technically valid. So can't check with !firstKey, have to see if has any defined value. */ return defined(firstKey) ? /* We know the first key of the newly parsed object. Notify that path has been found but don't put firstKey permanently onto pathList yet because we haven't identified what is at that key yet. Give null as the value because we haven't seen that far into the json yet */ pathFound(ascentAfterNodeFound, firstKey) : ascentAfterNodeFound ; }, openarray: function (ascent) { return nodeFound(ascent, []); }, // called by Clarinet when keys are found in objects key: pathFound, /* Emitted by Clarinet when primitive values are found, ie Strings, Numbers, and null. Because these are always leaves in the JSON, we find and finish the node in one step, expressed as functional composition: */ value: compose2( nodeFinished, nodeFound ), // we make no distinction in how we handle object and arrays closing. // For both, interpret as the end of the current node. closeobject: nodeFinished, closearray: nodeFinished }; } /** * The jsonPath evaluator compiler used for Oboe.js. * * One function is exposed. This function takes a String JSONPath spec and * returns a function to test candidate ascents for matches. * * String jsonPath -> (List ascent) -> Boolean|Object * * This file is coded in a pure functional style. That is, no function has * side effects, every function evaluates to the same value for the same * arguments and no variables are reassigned. */ // the call to jsonPathSyntax injects the token syntaxes that are needed // inside the compiler var jsonPathCompiler = jsonPathSyntax(function (pathNodeSyntax, doubleDotSyntax, dotSyntax, bangSyntax, emptySyntax ) { var CAPTURING_INDEX = 1; var NAME_INDEX = 2; var FIELD_LIST_INDEX = 3; var headKey = compose2(keyOf, head), headNode = compose2(nodeOf, head); /** * Create an evaluator function for a named path node, expressed in the * JSONPath like: * foo * ["bar"] * [2] */ function nameClause(previousExpr, detection ) { var name = detection[NAME_INDEX], matchesName = ( !name || name == '*' ) ? always : function(ascent){return headKey(ascent) == name}; return lazyIntersection(matchesName, previousExpr); } /** * Create an evaluator function for a a duck-typed node, expressed like: * * {spin, taste, colour} * .particle{spin, taste, colour} * *{spin, taste, colour} */ function duckTypeClause(previousExpr, detection) { var fieldListStr = detection[FIELD_LIST_INDEX]; if (!fieldListStr) return previousExpr; // don't wrap at all, return given expr as-is var hasAllrequiredFields = partialComplete( hasAllProperties, arrayAsList(fieldListStr.split(/\W+/)) ), isMatch = compose2( hasAllrequiredFields, headNode ); return lazyIntersection(isMatch, previousExpr); } /** * Expression for $, returns the evaluator function */ function capture( previousExpr, detection ) { // extract meaning from the detection var capturing = !!detection[CAPTURING_INDEX]; if (!capturing) return previousExpr; // don't wrap at all, return given expr as-is return lazyIntersection(previousExpr, head); } /** * Create an evaluator function that moves onto the next item on the * lists. This function is the place where the logic to move up a * level in the ascent exists. * * Eg, for JSONPath ".foo" we need skip1(nameClause(always, [,'foo'])) */ function skip1(previousExpr) { if( previousExpr == always ) { /* If there is no previous expression this consume command is at the start of the jsonPath. Since JSONPath specifies what we'd like to find but not necessarily everything leading down to it, when running out of JSONPath to check against we default to true */ return always; } /** return true if the ascent we have contains only the JSON root, * false otherwise */ function notAtRoot(ascent){ return headKey(ascent) != ROOT_PATH; } return lazyIntersection( /* If we're already at the root but there are more expressions to satisfy, can't consume any more. No match. This check is why none of the other exprs have to be able to handle empty lists; skip1 is the only evaluator that moves onto the next token and it refuses to do so once it reaches the last item in the list. */ notAtRoot, /* We are not at the root of the ascent yet. Move to the next level of the ascent by handing only the tail to the previous expression */ compose2(previousExpr, tail) ); } /** * Create an evaluator function for the .. (double dot) token. Consumes * zero or more levels of the ascent, the fewest that are required to find * a match when given to previousExpr. */ function skipMany(previousExpr) { if( previousExpr == always ) { /* If there is no previous expression this consume command is at the start of the jsonPath. Since JSONPath specifies what we'd like to find but not necessarily everything leading down to it, when running out of JSONPath to check against we default to true */ return always; } var // In JSONPath .. is equivalent to !.. so if .. reaches the root // the match has succeeded. Ie, we might write ..foo or !..foo // and both should match identically. terminalCaseWhenArrivingAtRoot = rootExpr(), terminalCaseWhenPreviousExpressionIsSatisfied = previousExpr, recursiveCase = skip1(skipManyInner), cases = lazyUnion( terminalCaseWhenArrivingAtRoot , terminalCaseWhenPreviousExpressionIsSatisfied , recursiveCase ); function skipManyInner(ascent) { if( !ascent ) { // have gone past the start, not a match: return false; } return cases(ascent); } return skipManyInner; } /** * Generate an evaluator for ! - matches only the root element of the json * and ignores any previous expressions since nothing may precede !. */ function rootExpr() { return function(ascent){ return headKey(ascent) == ROOT_PATH; }; } /** * Generate a statement wrapper to sit around the outermost * clause evaluator. * * Handles the case where the capturing is implicit because the JSONPath * did not contain a '$' by returning the last node. */ function statementExpr(lastClause) { return function(ascent) { // kick off the evaluation by passing through to the last clause var exprMatch = lastClause(ascent); return exprMatch === true ? head(ascent) : exprMatch; }; } /** * For when a token has been found in the JSONPath input. * Compiles the parser for that token and returns in combination with the * parser already generated. * * @param {Function} exprs a list of the clause evaluator generators for * the token that was found * @param {Function} parserGeneratedSoFar the parser already found * @param {Array} detection the match given by the regex engine when * the feature was found */ function expressionsReader( exprs, parserGeneratedSoFar, detection ) { // if exprs is zero-length foldR will pass back the // parserGeneratedSoFar as-is so we don't need to treat // this as a special case return foldR( function( parserGeneratedSoFar, expr ){ return expr(parserGeneratedSoFar, detection); }, parserGeneratedSoFar, exprs ); } /** * If jsonPath matches the given detector function, creates a function which * evaluates against every clause in the clauseEvaluatorGenerators. The * created function is propagated to the onSuccess function, along with * the remaining unparsed JSONPath substring. * * The intended use is to create a clauseMatcher by filling in * the first two arguments, thus providing a function that knows * some syntax to match and what kind of generator to create if it * finds it. The parameter list once completed is: * * (jsonPath, parserGeneratedSoFar, onSuccess) * * onSuccess may be compileJsonPathToFunction, to recursively continue * parsing after finding a match or returnFoundParser to stop here. */ function generateClauseReaderIfTokenFound ( tokenDetector, clauseEvaluatorGenerators, jsonPath, parserGeneratedSoFar, onSuccess) { var detected = tokenDetector(jsonPath); if(detected) { var compiledParser = expressionsReader( clauseEvaluatorGenerators, parserGeneratedSoFar, detected ), remainingUnparsedJsonPath = jsonPath.substr(len(detected[0])); return onSuccess(remainingUnparsedJsonPath, compiledParser); } } /** * Partially completes generateClauseReaderIfTokenFound above. */ function clauseMatcher(tokenDetector, exprs) { return partialComplete( generateClauseReaderIfTokenFound, tokenDetector, exprs ); } /** * clauseForJsonPath is a function which attempts to match against * several clause matchers in order until one matches. If non match the * jsonPath expression is invalid and an error is thrown. * * The parameter list is the same as a single clauseMatcher: * * (jsonPath, parserGeneratedSoFar, onSuccess) */ var clauseForJsonPath = lazyUnion( clauseMatcher(pathNodeSyntax , list( capture, duckTypeClause, nameClause, skip1 )) , clauseMatcher(doubleDotSyntax , list( skipMany)) // dot is a separator only (like whitespace in other languages) but // rather than make it a special case, use an empty list of // expressions when this token is found , clauseMatcher(dotSyntax , list() ) , clauseMatcher(bangSyntax , list( capture, rootExpr)) , clauseMatcher(emptySyntax , list( statementExpr)) , function (jsonPath) { throw Error('"' + jsonPath + '" could not be tokenised') } ); /** * One of two possible values for the onSuccess argument of * generateClauseReaderIfTokenFound. * * When this function is used, generateClauseReaderIfTokenFound simply * returns the compiledParser that it made, regardless of if there is * any remaining jsonPath to be compiled. */ function returnFoundParser(_remainingJsonPath, compiledParser){ return compiledParser } /** * Recursively compile a JSONPath expression. * * This function serves as one of two possible values for the onSuccess * argument of generateClauseReaderIfTokenFound, meaning continue to * recursively compile. Otherwise, returnFoundParser is given and * compilation terminates. */ function compileJsonPathToFunction( uncompiledJsonPath, parserGeneratedSoFar ) { /** * On finding a match, if there is remaining text to be compiled * we want to either continue parsing using a recursive call to * compileJsonPathToFunction. Otherwise, we want to stop and return * the parser that we have found so far. */ var onFind = uncompiledJsonPath ? compileJsonPathToFunction : returnFoundParser; return clauseForJsonPath( uncompiledJsonPath, parserGeneratedSoFar, onFind ); } /** * This is the function that we expose to the rest of the library. */ return function(jsonPath){ try { // Kick off the recursive parsing of the jsonPath return compileJsonPathToFunction(jsonPath, always); } catch( e ) { throw Error( 'Could not compile "' + jsonPath + '" because ' + e.message ); } } }); /** * A pub/sub which is responsible for a single event type. A * multi-event type event bus is created by pubSub by collecting * several of these. * * @param {String} eventType * the name of the events managed by this singleEventPubSub * @param {singleEventPubSub} [newListener] * place to notify of new listeners * @param {singleEventPubSub} [removeListener] * place to notify of when listeners are removed */ function singleEventPubSub(eventType, newListener, removeListener){ /** we are optimised for emitting events over firing them. * As well as the tuple list which stores event ids and * listeners there is a list with just the listeners which * can be iterated more quickly when we are emitting */ var listenerTupleList, listenerList; function hasId(id){ return function(tuple) { return tuple.id == id; }; } return { /** * @param {Function} listener * @param {*} listenerId * an id that this listener can later by removed by. * Can be of any type, to be compared to other ids using == */ on:function( listener, listenerId ) { var tuple = { listener: listener , id: listenerId || listener // when no id is given use the // listener function as the id }; if( newListener ) { newListener.emit(eventType, listener, tuple.id); } listenerTupleList = cons( tuple, listenerTupleList ); listenerList = cons( listener, listenerList ); return this; // chaining }, emit:function () { applyEach( listenerList, arguments ); }, un: function( listenerId ) { var removed; listenerTupleList = without( listenerTupleList, hasId(listenerId), function(tuple){ removed = tuple; } ); if( removed ) { listenerList = without( listenerList, function(listener){ return listener == removed.listener; }); if( removeListener ) { removeListener.emit(eventType, removed.listener, removed.id); } } }, listeners: function(){ // differs from Node EventEmitter: returns list, not array return listenerList; }, hasListener: function(listenerId){ var test = listenerId? hasId(listenerId) : always; return defined(first( test, listenerTupleList)); } }; } /** * pubSub is a curried interface for listening to and emitting * events. * * If we get a bus: * * var bus = pubSub(); * * We can listen to event 'foo' like: * * bus('foo').on(myCallback) * * And emit event foo like: * * bus('foo').emit() * * or, with a parameter: * * bus('foo').emit('bar') * * All functions can be cached and don't need to be * bound. Ie: * * var fooEmitter = bus('foo').emit * fooEmitter('bar'); // emit an event * fooEmitter('baz'); // emit another * * There's also an uncurried[1] shortcut for .emit and .on: * * bus.on('foo', callback) * bus.emit('foo', 'bar') * * [1]: http://zvon.org/other/haskell/Outputprelude/uncurry_f.html */ function pubSub(){ var singles = {}, newListener = newSingle('newListener'), removeListener = newSingle('removeListener'); function newSingle(eventName) { return singles[eventName] = singleEventPubSub( eventName, newListener, removeListener ); } /** pubSub instances are functions */ function pubSubInstance( eventName ){ return singles[eventName] || newSingle( eventName ); } // add convenience EventEmitter-style uncurried form of 'emit' and 'on' ['emit', 'on', 'un'].forEach(function(methodName){ pubSubInstance[methodName] = varArgs(function(eventName, parameters){ apply( parameters, pubSubInstance( eventName )[methodName]); }); }) return pubSubInstance; } /** * This file declares some constants to use as names for event types. */ var // the events which are never exported are kept as // the smallest possible representation, in numbers: _S = 1, // fired whenever a node is found in the JSON: NODE_FOUND = _S++, // fired whenever a path is found in the JSON: PATH_FOUND = _S++, FAIL_EVENT = 'fail', ROOT_FOUND = _S++, HTTP_START = 'start', STREAM_DATA = 'content', STREAM_END = _S++, ABORTING = _S++; function errorReport(statusCode, body, error) { try{ var jsonBody = JSON.parse(body); }catch(e){} return { statusCode:statusCode, body:body, jsonBody:jsonBody, thrown:error }; } function patternAdapter(oboeBus, jsonPathCompiler) { var predicateEventMap = { node:oboeBus(NODE_FOUND) , path:oboeBus(PATH_FOUND) }; function emitMatchingNode(emitMatch, node, ascent) { /* We're now calling to the outside world where Lisp-style lists will not be familiar. Convert to standard arrays. Also, reverse the order because it is more common to list paths "root to leaf" than "leaf to root" */ var descent = reverseList(ascent); emitMatch( node, // To make a path, strip off the last item which is the special // ROOT_PATH token for the 'path' to the root node listAsArray(tail(map(keyOf,descent))), // path listAsArray(map(nodeOf, descent)) // ancestors ); } function addUnderlyingListener( fullEventName, predicateEvent, compiledJsonPath ){ var emitMatch = oboeBus(fullEventName).emit; predicateEvent.on( function (ascent) { var maybeMatchingMapping = compiledJsonPath(ascent); /* Possible values for maybeMatchingMapping are now: false: we did not match an object/array/string/number/null: we matched and have the node that matched. Because nulls are valid json values this can be null. undefined: we matched but don't have the matching node yet. ie, we know there is an upcoming node that matches but we can't say anything else about it. */ if (maybeMatchingMapping !== false) { emitMatchingNode( emitMatch, nodeOf(maybeMatchingMapping), ascent ); } }, fullEventName); oboeBus('removeListener').on( function(removedEventName){ // if the match even listener is later removed, clean up by removing // the underlying listener if nothing else is using that pattern: if( removedEventName == fullEventName ) { if( !oboeBus(removedEventName).listeners( )) { predicateEvent.un( fullEventName ); } } }); } oboeBus('newListener').on( function(fullEventName){ var match = /(node|path):(.*)/.exec(fullEventName); if( match ) { var predicateEvent = predicateEventMap[match[1]]; if( !predicateEvent.hasListener( fullEventName) ) { addUnderlyingListener( fullEventName, predicateEvent, jsonPathCompiler( match[2] ) ); } } }) } /** * The instance API is the thing that is returned when oboe() is called. * it allows: * * - listeners for various events to be added and removed * - the http response header/headers to be read */ function instanceApi(oboeBus){ var oboeApi, fullyQualifiedNamePattern = /^(node|path):./, rootNodeFinishedEvent = oboeBus('node:!'), /** * Add any kind of listener that the instance api exposes */ addListener = varArgs(function( eventId, parameters ){ if( oboeApi[eventId] ) { // for events added as .on(event, callback), if there is a // .event() equivalent with special behaviour , pass through // to that: apply(parameters, oboeApi[eventId]); } else { // we have a standard Node.js EventEmitter 2-argument call. // The first parameter is the listener. var event = oboeBus(eventId), listener = parameters[0]; if( fullyQualifiedNamePattern.test(eventId) ) { // allow fully-qualified node/path listeners // to be added addForgettableCallback(event, listener); } else { // the event has no special handling, pass through // directly onto the event bus: event.on( listener); } } return oboeApi; // chaining }), /** * Remove any kind of listener that the instance api exposes */ removeListener = function( eventId, p2, p3 ){ if( eventId == 'done' ) { rootNodeFinishedEvent.un(p2); } else if( eventId == 'node' || eventId == 'path' ) { // allow removal of node and path oboeBus.un(eventId + ':' + p2, p3); } else { // we have a standard Node.js EventEmitter 2-argument call. // The second parameter is the listener. This may be a call // to remove a fully-qualified node/path listener but requires // no special handling var listener = p2; oboeBus(eventId).un(listener); } return oboeApi; // chaining }; /** * Add a callback, wrapped in a try/catch so as to not break the * execution of Oboe if an exception is thrown (fail events are * fired instead) * * The callback is used as the listener id so that it can later be * removed using .un(callback) */ function addProtectedCallback(eventName, callback) { oboeBus(eventName).on(protectedCallback(callback), callback); return oboeApi; // chaining } /** * Add a callback where, if .forget() is called during the callback's * execution, the callback will be de-registered */ function addForgettableCallback(event, callback) { var safeCallback = protectedCallback(callback); event.on( function() { var discard = false; oboeApi.forget = function(){ discard = true; }; apply( arguments, safeCallback ); delete oboeApi.forget; if( discard ) { event.un(callback); } }, callback) return oboeApi; // chaining } function protectedCallback( callback ) { return function() { try{ callback.apply(oboeApi, arguments); }catch(e) { // An error occured during the callback, publish it on the event bus oboeBus(FAIL_EVENT).emit( errorReport(undefined, undefined, e)); } } } /** * Return the fully qualified event for when a pattern matches * either a node or a path * * @param type {String} either 'node' or 'path' */ function fullyQualifiedPatternMatchEvent(type, pattern) { return oboeBus(type + ':' + pattern); } /** * Add several listeners at a time, from a map */ function addListenersMap(eventId, listenerMap) { for( var pattern in listenerMap ) { addForgettableCallback( fullyQualifiedPatternMatchEvent(eventId, pattern), listenerMap[pattern] ); } } /** * implementation behind .onPath() and .onNode() */ function addNodeOrPathListenerApi( eventId, jsonPathOrListenerMap, callback ){ if( isString(jsonPathOrListenerMap) ) { addForgettableCallback( fullyQualifiedPatternMatchEvent(eventId, jsonPathOrListenerMap), callback ); } else { addListenersMap(eventId, jsonPathOrListenerMap); } return oboeApi; // chaining } // some interface methods are only filled in after we recieve // values and are noops before that: oboeBus(ROOT_FOUND).on( function(root) { oboeApi.root = functor(root); }); /** * When content starts make the headers readable through the * instance API */ oboeBus(HTTP_START).on( function(_statusCode, headers) { oboeApi.header = function(name) { return name ? headers[name] : headers ; } }); /** * Construct and return the public API of the Oboe instance to be * returned to the calling application */ return oboeApi = { on : addListener, addListener : addListener, removeListener : removeListener, emit : oboeBus.emit, node : partialComplete(addNodeOrPathListenerApi, 'node'), path : partialComplete(addNodeOrPathListenerApi, 'path'), done : partialComplete(addForgettableCallback, rootNodeFinishedEvent), start : partialComplete(addProtectedCallback, HTTP_START ), // fail doesn't use protectedCallback because // could lead to non-terminating loops fail : oboeBus(FAIL_EVENT).on, // public api calling abort fires the ABORTING event abort : oboeBus(ABORTING).emit, // initially return nothing for header and root header : noop, root : noop }; } /** * This file implements a light-touch central controller for an instance * of Oboe which provides the methods used for interacting with the instance * from the calling app. */ function instanceController( oboeBus, clarinetParser, contentBuilderHandlers) { oboeBus(STREAM_DATA).on( clarinetParser.write.bind(clarinetParser)); /* At the end of the http content close the clarinet parser. This will provide an error if the total content provided was not valid json, ie if not all arrays, objects and Strings closed properly */ oboeBus(STREAM_END).on( clarinetParser.close.bind(clarinetParser)); /* If we abort this Oboe's request stop listening to the clarinet parser. This prevents more tokens being found after we abort in the case where we aborted during processing of an already filled buffer. */ oboeBus(ABORTING).on( function() { clarinetListenerAdaptor(clarinetParser, {}); }); clarinetListenerAdaptor(clarinetParser, contentBuilderHandlers); // react to errors by putting them on the event bus clarinetParser.onerror = function(e) { oboeBus(FAIL_EVENT).emit( errorReport(undefined, undefined, e) ); // note: don't close clarinet here because if it was not expecting // end of the json it will throw an error }; } /** * This file sits just behind the API which is used to attain a new * Oboe instance. It creates the new components that are required * and introduces them to each other. */ function wire (httpMethodName, contentSource, body, headers){ var oboeBus = pubSub(); // Wire the input stream in if we are given a content source. // This will usually be the case. If not, the instance created // will have to be passed content from an external source. if( contentSource ) { streamingHttp( oboeBus, httpTransport(), httpMethodName, contentSource, body, headers ); } instanceController( oboeBus, clarinet.parser(), incrementalContentBuilder(oboeBus) ); patternAdapter(oboeBus, jsonPathCompiler); return new instanceApi(oboeBus); } // export public API function oboe(arg1, arg2) { if( arg1 ) { if (arg1.url) { // method signature is: // oboe({method:m, url:u, body:b, headers:{...}}) return wire( (arg1.method || 'GET'), url(arg1.url, arg1.cached), arg1.body, arg1.headers ); } else { // simple version for GETs. Signature is: // oboe( url ) // return wire( 'GET', arg1, // url arg2 // body. Deprecated, use {url:u, body:b} instead ); } } else { // wire up a no-AJAX Oboe. Will have to have content // fed in externally and fed in using .emit. return wire(); } function url(baseUrl, cached) { if( cached === false ) { if( baseUrl.indexOf('?') == -1 ) { baseUrl += '?'; } else { baseUrl += '&'; } baseUrl += '_=' + new Date().getTime(); } return baseUrl; } } ;if ( typeof define === "function" && define.amd ) {define( "oboe", [], function () { return oboe; } );} else {window.oboe = oboe;}})(window, Object, Array, Error);
src/client/products/productFilter.js
r3dDoX/geekplanet
import Chip from '@material-ui/core/Chip'; import PropTypes from 'prop-types'; import queryString from 'query-string'; import React from 'react'; import { injectIntl } from 'react-intl'; import { withRouter } from 'react-router-dom'; import { Field, reduxForm } from 'redux-form'; import styled from 'styled-components'; import SmallTextField from '../formHelpers/smallTextField'; import { ProductCategoryPropType } from '../propTypes'; import theme from '../theme'; export const formName = 'productFilter'; const FilterContainer = styled.div` display: flex; align-items: center; justify-content: flex-start; flex-wrap: nowrap; background: #FFF; padding: 12px 20px; box-shadow: 0 0 10px -2px rgba(0, 0, 0, 0.3); max-height: 68px; overflow-x: auto; @media screen and (max-width: ${theme.breakpoints.values.md}px) { justify-content: space-between; } `; const SearchField = styled(Field)` min-width: 100px; `; const ChipContainer = styled.div` display: flex; align-items: center; justify-content: flex-start; `; const CategoryChip = styled(Chip)` margin-left: 10px !important; `; let timeoutId; function debounce(fn, millis = 200) { if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(fn, millis); } const ProductFilter = ({ categories, removeCategoryFromFilter, history, intl, }) => ( <FilterContainer> <SearchField component={SmallTextField} name="search" label={intl.formatMessage({ id: 'PRODUCT_FILTER.FILTERSTRING_PLACEHOLDER' })} onKeyUp={({ target }) => debounce(() => { const query = queryString.parse(history.location.search); query.search = target.value; delete query.page; history.push(`?${queryString.stringify(query)}`); })} type="text" /> <ChipContainer> {categories.map(category => ( <CategoryChip key={category._id} onDelete={() => removeCategoryFromFilter(category._id)} label={category.de.name} /> ))} </ChipContainer> </FilterContainer> ); ProductFilter.propTypes = { categories: PropTypes.arrayOf(ProductCategoryPropType).isRequired, removeCategoryFromFilter: PropTypes.func.isRequired, history: PropTypes.shape({ location: PropTypes.shape({ search: PropTypes.string.isRequired, }).isRequired, push: PropTypes.func.isRequired, }).isRequired, intl: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types }; export default reduxForm({ form: formName, destroyOnUnmount: false, })(withRouter(injectIntl(ProductFilter)));
examples/src/pages/page/WizardPage.js
nkiateam/polestar-antd
import React from 'react'; import Button from '../../../../src/Button'; import Wizard from '../../../../src/Wizard'; class WizardPage extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } openWizard = () => { this.setState({ open: true, }); }; closeWizard = () => { this.setState({ open: false, }); }; render() { return ( <div> <Button onClick={this.openWizard}>위자드 열기</Button> <Wizard stepPosition="left" width={1000} modal open={this.state.open} onPrev={() => { console.log('prev'); }} onDone={() => { console.log('done'); this.closeWizard(); }} onNext={() => { console.log('next'); }} onCancel={this.closeWizard} customButtons={[ <Button>커스텀버튼1</Button>, <Button>커스텀버튼2</Button>, <Button>커스텀버튼3</Button>, ]} > <Wizard.Step title="Step1" description="step1 description"> What is Lorem Ipsum? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc. </Wizard.Step> <Wizard.Step title="Step2" description="step2 description" message="hello" > Step2 </Wizard.Step> <Wizard.Step title="Step3" description="step3 description"> Step3 </Wizard.Step> </Wizard> </div> ); } } export default WizardPage;
example/src/screens/ImageGallery.js
callstack-io/react-native-material-palette
/* @flow */ import React, { Component } from 'react'; import { FlatList, Image, View, Text, ActivityIndicator, StyleSheet, } from 'react-native'; import { createMaterialPalette } from 'react-native-material-palette'; export default class ImageGallery extends Component { static navigationOptions = { title: 'Image Gallery', }; state = { data: [], error: null, }; componentDidMount() { this._loadPalettes(); } _loadPalettes = async () => { const words = [ 'Daleks', 'Thals', 'Voord', 'Sensorites', 'Koquillion', 'Menoptera', 'Zarbi', 'Larvae guns', 'Xerons', 'Aridians', 'Mire Beasts', 'Drahvins', ]; const urls = Array.from({ length: 12 }).map( (_, i) => `https://unsplash.it/300?random&num=${i * 100}`, ); let palettes; try { palettes = await Promise.all( urls.map(url => createMaterialPalette({ uri: url }, { type: 'muted' })), ); } catch (error) { this.setState({ error, }); return; } this.setState({ data: palettes.map((palette, i) => ({ palette, url: urls[i], label: words[i], key: urls[i], })), }); }; render() { if (this.state.error) { return ( <View style={[styles.blankslate, styles.error]}> <Text style={{ color: 'white' }}> An error occurred: {this.state.error.message} </Text> </View> ); } if (!this.state.data.length) { return ( <View style={styles.blankslate}> <ActivityIndicator /> </View> ); } return ( <FlatList data={this.state.data} numColumns={3} renderItem={({ item }) => ( <View style={styles.container}> <Image source={{ uri: item.url }} style={styles.image} /> <View style={[ styles.label, { backgroundColor: item.palette.muted.color, }, ]} > <Text style={{ color: item.palette.muted.bodyTextColor }}> {item.label} </Text> </View> </View> )} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, image: { minWidth: 120, maxWidth: 180, height: 120, }, blankslate: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 24, }, error: { backgroundColor: 'red', }, label: { padding: 8, }, });
src/svg-icons/communication/import-contacts.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationImportContacts = (props) => ( <SvgIcon {...props}> <path d="M21 5c-1.11-.35-2.33-.5-3.5-.5-1.95 0-4.05.4-5.5 1.5-1.45-1.1-3.55-1.5-5.5-1.5S2.45 4.9 1 6v14.65c0 .25.25.5.5.5.1 0 .15-.05.25-.05C3.1 20.45 5.05 20 6.5 20c1.95 0 4.05.4 5.5 1.5 1.35-.85 3.8-1.5 5.5-1.5 1.65 0 3.35.3 4.75 1.05.1.05.15.05.25.05.25 0 .5-.25.5-.5V6c-.6-.45-1.25-.75-2-1zm0 13.5c-1.1-.35-2.3-.5-3.5-.5-1.7 0-4.15.65-5.5 1.5V8c1.35-.85 3.8-1.5 5.5-1.5 1.2 0 2.4.15 3.5.5v11.5z"/> </SvgIcon> ); CommunicationImportContacts = pure(CommunicationImportContacts); CommunicationImportContacts.displayName = 'CommunicationImportContacts'; CommunicationImportContacts.muiName = 'SvgIcon'; export default CommunicationImportContacts;
admin/src/components/SecondaryNavigation.js
belafontestudio/keystone
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; import { Container } from 'elemental'; var SecondaryNavItem = React.createClass({ displayName: 'SecondaryNavItem', propTypes: { className: React.PropTypes.string, children: React.PropTypes.node.isRequired, href: React.PropTypes.string.isRequired, title: React.PropTypes.string, }, render () { return ( <li className={this.props.className}> <a href={this.props.href} title={this.props.title} tabIndex="-1"> {this.props.children} </a> </li> ); }, }); var SecondaryNavigation = React.createClass({ displayName: 'SecondaryNavigation', propTypes: { currentListKey: React.PropTypes.string, lists: React.PropTypes.array.isRequired, }, getInitialState() { return {}; }, componentDidMount: function() { this.handleResize(); window.addEventListener('resize', this.handleResize); }, componentWillUnmount: function() { window.removeEventListener('resize', this.handleResize); }, handleResize: function() { this.setState({ navIsVisible: this.props.lists && this.props.lists.length > 1 && window.innerWidth >= 768 }); }, renderNavigation (lists) { let navigation = lists.map((list) => { let href = list.external ? list.path : ('/keystone/' + list.path); let className = (this.props.currentListKey && this.props.currentListKey === list.path) ? 'active' : null; return ( <SecondaryNavItem key={list.path} className={className} href={href}> {list.label} </SecondaryNavItem> ); }); return ( <ul className="app-nav app-nav--secondary app-nav--left"> {navigation} </ul> ); }, render () { if (!this.state.navIsVisible) return null; return ( <nav className="secondary-navbar"> <Container clearfix> {this.renderNavigation(this.props.lists)} </Container> </nav> ); } }); module.exports = SecondaryNavigation;
src/base/routes/index.js
pmagaz/pablomagaz.com
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from 'containers/App/'; import Blog from 'containers/Blog/'; import Main from 'containers/Main/'; import Post from 'containers/Post/'; const routes = ( <Route path="/" component={ App }> <IndexRoute component={ Main } /> <Route path="/main" component={ Main } /> <Route path="/blog" component={ Blog } /> <Route path="/tag/:tag" component={ Blog } /> <Route path="/blog/:slug" component={ Post } /> <Route path="/blog/page/:page" component={ Blog } /> </Route> ); export default routes;
ajax/libs/vue-material/1.0.0-beta-7/components/MdSpeedDial/index.js
ahocevar/cdnjs
!(function(e,t){var n,r;if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("vue"));else if("function"==typeof define&&define.amd)define(["vue"],t);else{n=t("object"==typeof exports?require("vue"):e.Vue);for(r in n)("object"==typeof exports?exports:e)[r]=n[r]}})(this,(function(e){return (function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=424)})({0:function(e,t){e.exports=function(e,t,n,r,o,i){var u,a,s,l,c,d=e=e||{},f=typeof e.default;return"object"!==f&&"function"!==f||(u=e,d=e.default),a="function"==typeof d?d.options:d,t&&(a.render=t.render,a.staticRenderFns=t.staticRenderFns,a._compiled=!0),n&&(a.functional=!0),o&&(a._scopeId=o),i?(s=function(e){e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,e||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(i)},a._ssrRegister=s):r&&(s=r),s&&(l=a.functional,c=l?a.render:a.beforeCreate,l?(a._injectStyles=s,a.render=function(e,t){return s.call(t),c(e,t)}):a.beforeCreate=c?[].concat(c,s):[s]),{esModule:u,exports:d,options:a}}},1:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var o,i,u,a;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t={props:{mdTheme:null},computed:{$mdActiveTheme:function(){var e=i.default.enabled,t=i.default.getThemeName,n=i.default.getAncestorTheme;return e&&!1!==this.mdTheme?t(this.mdTheme||n(this)):null}}};return(0,a.default)(t,e)},o=n(4),i=r(o),u=n(6),a=r(u)},12:function(e,t,n){(function(t){var r,o,i,u,a,s=n(15),l="undefined"==typeof window?t:window,c=["moz","webkit"],d="AnimationFrame",f=l["request"+d],p=l["cancel"+d]||l["cancelRequest"+d];for(r=0;!f&&r<c.length;r++)f=l[c[r]+"Request"+d],p=l[c[r]+"Cancel"+d]||l[c[r]+"CancelRequest"+d];f&&p||(o=0,i=0,u=[],a=1e3/60,f=function(e){if(0===u.length){var t=s(),n=Math.max(0,a-(t-o));o=n+t,setTimeout((function(){var e,t=u.slice(0);for(u.length=0,e=0;e<t.length;e++)if(!t[e].cancelled)try{t[e].callback(o)}catch(e){setTimeout((function(){throw e}),0)}}),Math.round(n))}return u.push({handle:++i,callback:e,cancelled:!1}),i},p=function(e){for(var t=0;t<u.length;t++)u[t].handle===e&&(u[t].cancelled=!0)}),e.exports=function(e){return f.call(l,e)},e.exports.cancel=function(){p.apply(l,arguments)},e.exports.polyfill=function(e){e||(e=l),e.requestAnimationFrame=f,e.cancelAnimationFrame=p}}).call(t,n(13))},13:function(e,t){var n;n=(function(){return this})();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},14:function(e,t,n){"use strict";function r(e){n(17)}var o,i,u,a,s,l,c,d,f,p,m,h;Object.defineProperty(t,"__esModule",{value:!0}),o=n(18),i=n.n(o),u=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"md-ripple",class:e.rippleClasses,on:{"&touchstart":function(t){t.stopPropagation(),e.touchStartCheck(t)},"&touchmove":function(t){t.stopPropagation(),e.touchMoveCheck(t)},"&mousedown":function(t){t.stopPropagation(),e.startRipple(t)}}},[e._t("default"),e._v(" "),e.isDisabled?e._e():n("transition",{attrs:{name:"md-ripple"},on:{"after-enter":e.clearWave}},[e.animating?n("span",{ref:"rippleWave",staticClass:"md-ripple-wave",class:e.waveClasses,style:e.waveStyles}):e._e()])],2)},a=[],s={render:u,staticRenderFns:a},l=s,c=n(0),d=!1,f=r,p=null,m=null,h=c(i.a,l,d,f,p,m),t.default=h.exports},15:function(e,t,n){(function(t){(function(){var n,r,o,i,u,a;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:void 0!==t&&null!==t&&t.hrtime?(e.exports=function(){return(n()-u)/1e6},r=t.hrtime,n=function(){var e;return e=r(),1e9*e[0]+e[1]},i=n(),a=1e9*t.uptime(),u=i-a):Date.now?(e.exports=function(){return Date.now()-o},o=Date.now()):(e.exports=function(){return(new Date).getTime()-o},o=(new Date).getTime())}).call(this)}).call(t,n(16))},16:function(e,t){function n(){throw Error("setTimeout has not been defined")}function r(){throw Error("clearTimeout has not been defined")}function o(e){if(c===setTimeout)return setTimeout(e,0);if((c===n||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function i(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(t){try{return d.call(null,e)}catch(t){return d.call(this,e)}}}function u(){p&&m&&(p=!1,m.length?f=m.concat(f):h=-1,f.length&&a())}function a(){var e,t;if(!p){for(e=o(u),p=!0,t=f.length;t;){for(m=f,f=[];++h<t;)m&&m[h].run();h=-1,t=f.length}m=null,p=!1,i(e)}}function s(e,t){this.fun=e,this.array=t}function l(){}var c,d,f,p,m,h,v=e.exports={};!(function(){try{c="function"==typeof setTimeout?setTimeout:n}catch(e){c=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(e){d=r}})(),f=[],p=!1,h=-1,v.nextTick=function(e){var t,n=Array(arguments.length-1);if(arguments.length>1)for(t=1;t<arguments.length;t++)n[t-1]=arguments[t];f.push(new s(e,n)),1!==f.length||p||o(a)},s.prototype.run=function(){this.fun.apply(null,this.array)},v.title="browser",v.browser=!0,v.env={},v.argv=[],v.version="",v.versions={},v.on=l,v.addListener=l,v.once=l,v.off=l,v.removeListener=l,v.removeAllListeners=l,v.emit=l,v.prependListener=l,v.prependOnceListener=l,v.listeners=function(e){return[]},v.binding=function(e){throw Error("process.binding is not supported")},v.cwd=function(){return"/"},v.chdir=function(e){throw Error("process.chdir is not supported")},v.umask=function(){return 0}},17:function(e,t){},18:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(o,i){var u,a;try{u=t[o](i),a=u.value}catch(e){return void n(e)}if(!u.done)return Promise.resolve(a).then((function(e){r("next",e)}),(function(e){r("throw",e)}));e(a)}return r("next")})}}var i,u,a,s,l;Object.defineProperty(t,"__esModule",{value:!0}),i=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(12),a=r(u),s=n(1),l=r(s),t.default=new l.default({name:"MdRipple",props:{mdActive:null,mdDisabled:Boolean,mdCentered:Boolean},data:function(){return{eventType:null,waveStyles:null,animating:!1,touchTimeout:null}},computed:{isDisabled:function(){return!this.$material.ripple||this.mdDisabled},rippleClasses:function(){return{"md-disabled":this.isDisabled}},waveClasses:function(){return{"md-centered":this.mdCentered}}},watch:{mdActive:function(e){var t="boolean"==typeof e,n="mouseevent"===e.constructor.name.toLowerCase();t&&this.mdCentered&&e?(this.startRipple({type:"mousedown"}),this.$emit("update:mdActive",!1)):n&&(this.startRipple(e),this.$emit("update:mdActive",!1))}},methods:{touchMoveCheck:function(){window.clearTimeout(this.touchTimeout)},touchStartCheck:function(e){var t=this;this.touchTimeout=window.setTimeout((function(){t.startRipple(e)}),100)},startRipple:function(e){var t=this;(0,a.default)(o(regeneratorRuntime.mark((function n(){var r,o,i,u,a;return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r=t.eventType,o=t.isDisabled,i=t.mdCentered,o||r&&r!==e.type){n.next=10;break}return u=t.getSize(),a=null,a=i?t.getCenteredPosition(u):t.getHitPosition(e,u),n.next=7,t.clearWave();case 7:t.eventType=e.type,t.animating=!0,t.applyStyles(a,u);case 10:case"end":return n.stop()}}),n,t)}))))},applyStyles:function(e,t){t+="px",this.waveStyles=i({},e,{width:t,height:t})},clearWave:function(){return this.waveStyles=null,this.animating=!1,this.$nextTick()},getSize:function(){var e=this.$el,t=e.offsetWidth,n=e.offsetHeight;return Math.round(Math.max(t,n))},getCenteredPosition:function(e){var t=-e/2+"px";return{"margin-top":t,"margin-left":t}},getHitPosition:function(e,t){var n=this.$el.getBoundingClientRect(),r=e.pageY,o=e.pageX;return"touchstart"===e.type&&(r=e.changedTouches[0].pageY,o=e.changedTouches[0].pageX),{top:r-n.top-t/2-document.documentElement.scrollTop+"px",left:o-n.left-t/2-document.documentElement.scrollLeft+"px"}}}})},2:function(t,n){t.exports=e},20:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.default=function(e,t){return r({},t,e.$options.components["router-link"].options.props)}},27:function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),r=n(14),o=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default={components:{MdRipple:o.default},props:{mdRipple:{type:Boolean,default:!0}}}},28:function(e,t,n){"use strict";function r(e){n(32)}var o,i,u,a,s,l,c,d,f;Object.defineProperty(t,"__esModule",{value:!0}),o=n(33),i=n.n(o),u=n(0),a=null,s=!1,l=r,c=null,d=null,f=u(i.a,a,s,l,c,d),t.default=f.exports},29:function(e,t,n){"use strict";function r(){try{var e=Object.defineProperty({},"passive",{get:function(){v={passive:!0}}});window.addEventListener("ghost",null,e)}catch(e){}}function o(e){var t=(e.keyCode,e.target);y.currentElement=t}function i(e){y.currentElement=null}function u(){h.addEventListener("keyup",o)}function a(){h.addEventListener("pointerup",i)}function s(){h.addEventListener("MSPointerUp",i)}function l(){h.addEventListener("mouseup",i),"ontouchend"in window&&h.addEventListener("touchend",i,v)}function c(){window.PointerEvent?a():window.MSPointerEvent?s():l(),u()}function d(){m||(h=document.body,r(),c(),m=!0)}var f,p,m,h,v,y;Object.defineProperty(t,"__esModule",{value:!0}),f=n(5),p=(function(e){return e&&e.__esModule?e:{default:e}})(f),m=!1,h=null,v=!1,y=new p.default({currentElement:null}),t.default={data:function(){return{mdHasFocus:!1}},computed:{focusedElement:function(){return y.currentElement}},watch:{focusedElement:function(e){this.mdHasFocus=e===this.$el}},mounted:function(){d()}}},3:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var o,i,u,a,s;Object.defineProperty(t,"__esModule",{value:!0}),n(7),o=n(5),i=r(o),u=n(4),a=r(u),s=function(){var e=new i.default({ripple:!0,theming:{},locale:{startYear:1900,endYear:2099,dateFormat:"YYYY-MM-DD",days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shorterDays:["S","M","T","W","T","F","S"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"],shorterMonths:["J","F","M","A","M","Ju","Ju","A","Se","O","N","D"]}});return Object.defineProperties(e.theming,{metaColors:{get:function(){return a.default.metaColors},set:function(e){a.default.metaColors=e}},theme:{get:function(){return a.default.theme},set:function(e){a.default.theme=e}},enabled:{get:function(){return a.default.enabled},set:function(e){a.default.enabled=e}}}),e},t.default=function(e){e.material||(e.material=s(),e.prototype.$material=e.material)}},308:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var o,i,u,a,s,l,c,d;Object.defineProperty(t,"__esModule",{value:!0}),o=n(3),i=r(o),u=n(309),a=r(u),s=n(312),l=r(s),c=n(315),d=r(c),t.default=function(e){(0,i.default)(e),e.component(a.default.name,a.default),e.component(l.default.name,l.default),e.component(d.default.name,d.default)}},309:function(e,t,n){"use strict";function r(e){n(310)}var o,i,u,a,s,l,c,d,f,p,m,h;Object.defineProperty(t,"__esModule",{value:!0}),o=n(311),i=n.n(o),u=function(){var e=this,t=e.$createElement;return(e._self._c||t)("div",{staticClass:"md-speed-dial",class:[e.$mdActiveTheme,e.speedDialClasses]},[e._t("default")],2)},a=[],s={render:u,staticRenderFns:a},l=s,c=n(0),d=!1,f=r,p=null,m=null,h=c(i.a,l,d,f,p,m),t.default=h.exports},310:function(e,t){},311:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var i,u,a,s,l;Object.defineProperty(t,"__esModule",{value:!0}),i=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),a=r(u),s=n(8),l=r(s),t.default=new a.default({name:"MdSpeedDial",props:{mdEvent:i({type:String,default:"hover"},(0,l.default)("md-event",["click","hover"])),mdDirection:i({type:String,default:"top"},(0,l.default)("md-direction",["top","bottom"])),mdEffect:i({type:String,default:"fling"},(0,l.default)("md-effect",["fling","scale","opacity"]))},data:function(){return{MdSpeedDial:{active:!1,event:this.mdEvent,direction:this.mdDirection}}},provide:function(){return{MdSpeedDial:this.MdSpeedDial}},computed:{speedDialClasses:function(){var e;return e={"md-active":this.MdSpeedDial.active,"md-with-hover":"hover"===this.mdEvent},o(e,"md-direction-"+this.mdDirection,!0),o(e,"md-effect-"+this.mdEffect,!0),e}}})},312:function(e,t,n){"use strict";function r(e){n(313)}var o,i,u,a,s,l,c,d,f,p,m,h;Object.defineProperty(t,"__esModule",{value:!0}),o=n(314),i=n.n(o),u=function(){var e=this,t=e.$createElement;return(e._self._c||t)("md-button",e._g(e._b({staticClass:"md-speed-dial-target md-fab",on:{click:e.handleClick}},"md-button",e.$attrs,!1),e.$listeners),[e._t("default")],2)},a=[],s={render:u,staticRenderFns:a},l=s,c=n(0),d=!1,f=r,p=null,m=null,h=c(i.a,l,d,f,p,m),t.default=h.exports},313:function(e,t){},314:function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),r=n(28),o=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default={name:"MdSpeedDialTarget",components:{MdButton:o.default},inject:["MdSpeedDial"],methods:{handleClick:function(){"click"===this.MdSpeedDial.event&&(this.MdSpeedDial.active=!this.MdSpeedDial.active)}}}},315:function(e,t,n){"use strict";function r(e){n(316)}var o,i,u,a,s,l,c,d,f,p,m,h;Object.defineProperty(t,"__esModule",{value:!0}),o=n(317),i=n.n(o),u=function(){var e=this,t=e.$createElement;return(e._self._c||t)("div",{staticClass:"md-speed-dial-content"},[e._t("default")],2)},a=[],s={render:u,staticRenderFns:a},l=s,c=n(0),d=!1,f=r,p=null,m=null,h=c(i.a,l,d,f,p,m),t.default=h.exports},316:function(e,t){},317:function(e,t,n){"use strict";function r(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(o,i){var u,a;try{u=t[o](i),a=u.value}catch(e){return void n(e)}if(!u.done)return Promise.resolve(a).then((function(e){r("next",e)}),(function(e){r("throw",e)}));e(a)}return r("next")})}}function o(e,t,n){return"top"===e?n-t-1:t}Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"MdSpeedDialContent",inject:["MdSpeedDial"],methods:{setChildrenIndexes:(function(){function e(){return t.apply(this,arguments)}var t=r(regeneratorRuntime.mark((function e(){var t,n=this;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.$nextTick();case 2:t=this.$children.length,this.$children.forEach((function(e,r){if("button"===e._vnode.tag){var i=o(n.MdSpeedDial.direction,r,t);e.$el.setAttribute("md-button-index",i),e.$el.classList.add("md-raised")}}));case 4:case"end":return e.stop()}}),e,this)})));return e})()},mounted:function(){this.setChildrenIndexes()},updated:function(){this.setChildrenIndexes()}}},32:function(e,t){},33:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var o,i,u,a,s,l,c,d,f,p,m;Object.defineProperty(t,"__esModule",{value:!0}),o=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),a=n(29),s=r(a),l=n(27),c=r(l),d=n(20),f=r(d),p=n(34),m=r(p),t.default=new u.default({name:"MdButton",components:{MdButtonContent:m.default},mixins:[c.default,s.default],props:{href:String,type:{type:String,default:"button"},disabled:Boolean,to:null},render:function(e){var t=e("md-button-content",{attrs:{mdRipple:this.mdRipple,disabled:this.disabled}},this.$slots.default),n={staticClass:"md-button",class:[this.$mdActiveTheme,{"md-ripple-off":!this.mdRipple,"md-focused":this.mdHasFocus}],attrs:o({},this.attrs,{href:this.href,disabled:this.disabled,type:!this.href&&(this.type||"button")}),on:this.$listeners},r="button";return this.href?r="a":this.$router&&this.to&&(this.$options.props=(0,f.default)(this,this.$options.props),r="router-link",n.props=this.$props,delete n.props.type,delete n.attrs.type,delete n.props.href,delete n.attrs.href),e(r,n,[t])}})},34:function(e,t,n){"use strict";function r(e){n(35)}var o,i,u,a,s,l,c,d,f,p,m,h;Object.defineProperty(t,"__esModule",{value:!0}),o=n(36),i=n.n(o),u=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("md-ripple",{attrs:{"md-disabled":!e.mdRipple||e.disabled}},[n("div",{staticClass:"md-button-content"},[e._t("default")],2)])},a=[],s={render:u,staticRenderFns:a},l=s,c=n(0),d=!1,f=r,p=null,m=null,h=c(i.a,l,d,f,p,m),t.default=h.exports},35:function(e,t){},36:function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),r=n(14),o=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default={name:"MdButtonContent",components:{MdRipple:o.default},props:{mdRipple:Boolean,disabled:Boolean}}},4:function(e,t,n){"use strict";var r,o,i,u,a;Object.defineProperty(t,"__esModule",{value:!0}),r=n(2),o=(function(e){return e&&e.__esModule?e:{default:e}})(r),i=null,u=null,a=null,t.default=new o.default({data:function(){return{prefix:"md-theme-",theme:"default",enabled:!0,metaColors:!1}},computed:{themeTarget:function(){return!this.$isServer&&document.documentElement},fullThemeName:function(){return this.getThemeName()}},watch:{enabled:{immediate:!0,handler:function(){var e=this.fullThemeName,t=this.themeTarget,n=this.enabled;t&&(n?(t.classList.add(e),this.metaColors&&this.setHtmlMetaColors(e)):(t.classList.remove(e),this.metaColors&&this.setHtmlMetaColors()))}},theme:function(e,t){var n=this.getThemeName,r=this.themeTarget;e=n(e),r.classList.remove(n(t)),r.classList.add(e),this.metaColors&&this.setHtmlMetaColors(e)},metaColors:function(e){e?this.setHtmlMetaColors(this.fullThemeName):this.setHtmlMetaColors()}},methods:{getAncestorTheme:function(e){var t,n=this;return e?(t=e.mdTheme,(function e(r){if(r){var o=r.mdTheme,i=r.$parent;return o&&o!==t?o:e(i)}return n.theme})(e.$parent)):null},getThemeName:function(e){var t=e||this.theme;return this.prefix+t},setMicrosoftColors:function(e){i&&i.setAttribute("content",e)},setThemeColors:function(e){u&&u.setAttribute("content",e)},setMaskColors:function(e){a&&a.setAttribute("color",e)},setHtmlMetaColors:function(e){var t,n="#fff";e&&(t=window.getComputedStyle(document.documentElement),n=t.getPropertyValue("--"+e+"-primary")),n&&(this.setMicrosoftColors(n),this.setThemeColors(n),this.setMaskColors(n))}},mounted:function(){var e=this;i=document.querySelector('[name="msapplication-TileColor"]'),u=document.querySelector('[name="theme-color"]'),a=document.querySelector('[rel="mask-icon"]'),this.enabled&&this.metaColors&&window.addEventListener("load",(function(){e.setHtmlMetaColors(e.fullThemeName)}))}})},424:function(e,t,n){e.exports=n(308)},5:function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t={};return o.default.util.defineReactive(t,"reactive",e),t.reactive},r=n(2),o=(function(e){return e&&e.__esModule?e:{default:e}})(r)},6:function(e,t,n){"use strict";function r(e){return!!e&&"object"==typeof e}function o(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||i(e)}function i(e){return e.$$typeof===p}function u(e){return Array.isArray(e)?[]:{}}function a(e,t){return t&&!1===t.clone||!d(e)?e:c(u(e),e,t)}function s(e,t,n){return e.concat(t).map((function(e){return a(e,n)}))}function l(e,t,n){var r={};return d(e)&&Object.keys(e).forEach((function(t){r[t]=a(e[t],n)})),Object.keys(t).forEach((function(o){d(t[o])&&e[o]?r[o]=c(e[o],t[o],n):r[o]=a(t[o],n)})),r}function c(e,t,n){var r=Array.isArray(t),o=Array.isArray(e),i=n||{arrayMerge:s};return r===o?r?(i.arrayMerge||s)(e,t,n):l(e,t,n):a(t,n)}var d,f,p,m;Object.defineProperty(t,"__esModule",{value:!0}),d=function(e){return r(e)&&!o(e)},f="function"==typeof Symbol&&Symbol.for,p=f?Symbol.for("react.element"):60103,c.all=function(e,t){if(!Array.isArray(e))throw Error("first argument should be an array");return e.reduce((function(e,n){return c(e,n,t)}),{})},m=c,t.default=m},7:function(e,t){},8:function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),r=n(2),o=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default=function(e,t){return{validator:function(n){return!!t.includes(n)||(o.default.util.warn("The "+e+" prop is invalid. Given value: "+n+". Available options: "+t.join(", ")+".",void 0),!1)}}}}})}));
docs/src/pages/layout/grid/ComplexGrid.js
Kagami/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import Typography from '@material-ui/core/Typography'; import ButtonBase from '@material-ui/core/ButtonBase'; const styles = theme => ({ root: { flexGrow: 1, }, paper: { padding: theme.spacing.unit * 2, margin: 'auto', maxWidth: 500, }, image: { width: 128, height: 128, }, img: { margin: 'auto', display: 'block', maxWidth: '100%', maxHeight: '100%', }, }); function ComplexGrid(props) { const { classes } = props; return ( <div className={classes.root}> <Paper className={classes.paper}> <Grid container spacing={16}> <Grid item> <ButtonBase className={classes.image}> <img className={classes.img} alt="complex" src="/static/images/grid/complex.jpg" /> </ButtonBase> </Grid> <Grid item xs={12} sm container> <Grid item xs container direction="column" spacing={16}> <Grid item xs> <Typography gutterBottom variant="subtitle1"> Standard license </Typography> <Typography gutterBottom>Full resolution 1920x1080 • JPEG</Typography> <Typography color="textSecondary">ID: 1030114</Typography> </Grid> <Grid item> <Typography style={{ cursor: 'pointer' }}>Remove</Typography> </Grid> </Grid> <Grid item> <Typography variant="subtitle1">$19.00</Typography> </Grid> </Grid> </Grid> </Paper> </div> ); } ComplexGrid.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ComplexGrid);
examples/js/remote/remote-export-csv.js
prajapati-parth/react-bootstrap-table
import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; export default class RemoteExportCSV extends React.Component { constructor(props) { super(props); } render() { return ( <BootstrapTable data={ this.props.data } remote={ true } exportCSV={ true } options={ { onExportToCSV: this.props.onExportToCSV } }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/components/Todo/index.js
elemus/react-redux-todo-example
import React from 'react'; import PropTypes from 'prop-types'; import TaskList from './TaskList'; import Form from './Form'; const Todo = props => ( <div className="mt-3 col-xs-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2"> <h1>ToDo list</h1> <Form onTaskAdd={props.onTaskAdd} /> <TaskList tasks={props.tasks} onTaskToggle={props.onTaskToggle} onTaskDelete={props.onTaskDelete} /> </div> ); Todo.propTypes = { tasks: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, description: PropTypes.string.isRequired, isDone: PropTypes.bool.isRequired, })).isRequired, onTaskAdd: PropTypes.func.isRequired, onTaskToggle: PropTypes.func.isRequired, onTaskDelete: PropTypes.func.isRequired, }; export default Todo;
docs/tutorial/DO_NOT_TOUCH/07/src/components/Toast/index.js
idream3/cerebral
import React from 'react' import {connect} from 'cerebral/react' import {state} from 'cerebral/tags' export default connect({ toast: state`toast` }, function Toast (props) { if (!props.toast) { return null } return ( <div className='c-alerts c-alerts--bottomright'> <div className={`c-alert ${props.toast.type ? 'c-alert--' + props.toast.type : ''}`}> {props.toast.message} </div> </div> ) } )
src/components/molecules/Form/_stories.js
ygoto3/artwork-manager
import React from 'react'; import { action } from '@storybook/addon-actions'; import { Form } from './index'; module.exports = stories => ( stories .addWithInfo( 'normal', 'A button with a text label', () => ( <Form> <input type="text" name="title" /> <input type="text" name="imageSource" /> <textarea id="" name="description" cols="30" rows="10"></textarea> <button type="button" onClick={action('submitted')}>Register</button> </Form> ) ) );
pages/legal/terms-of-use/index.js
blockstack/blockstack-site
import React from 'react' import Content from '../../../common/markdown/terms-of-service.md' import { Section } from '@components/section' const meta = { path: '/legal/terms-of-use', title: 'Terms of Use' } class TermsOfUsePage extends React.PureComponent { static async getInitialProps(ctx) { return { meta } } render() { return ( <Section> <Section.Pane width={1}> <Section.Title is="h2" pb={5}> {meta.title} </Section.Title> <Content /> </Section.Pane> </Section> ) } } export default TermsOfUsePage
src/components/Modal/ModalProvider.js
cantonjs/re-admin
import React, { Component } from 'react'; import PropTypes from 'utils/PropTypes'; import ModalControllerStore from './ModalControllerStore'; import ModalControllerContext from './ModalControllerContext'; import ModalPortal from './ModalPortal'; export default class ModalProvider extends Component { static propTypes = { modalController: PropTypes.object, children: PropTypes.node, component: PropTypes.component, }; static defaultProps = { component: 'div', }; modalController = new ModalControllerStore(this.props.modalController); render() { const { component: Wrap, children, modalController, ...other } = this.props; return ( <ModalControllerContext.Provider value={this.modalController}> <Wrap {...other}> {children} <ModalPortal /> </Wrap> </ModalControllerContext.Provider> ); } }
node_modules/[email protected]@babel-traverse/lib/path/lib/virtual-types.js
ligangwolai/blog
"use strict"; exports.__esModule = true; exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined; var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var ReferencedIdentifier = exports.ReferencedIdentifier = { types: ["Identifier", "JSXIdentifier"], checkPath: function checkPath(_ref, opts) { var node = _ref.node, parent = _ref.parent; if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { if (t.isJSXIdentifier(node, opts)) { if (_babelTypes.react.isCompatTag(node.name)) return false; } else { return false; } } return t.isReferenced(node, parent); } }; var ReferencedMemberExpression = exports.ReferencedMemberExpression = { types: ["MemberExpression"], checkPath: function checkPath(_ref2) { var node = _ref2.node, parent = _ref2.parent; return t.isMemberExpression(node) && t.isReferenced(node, parent); } }; var BindingIdentifier = exports.BindingIdentifier = { types: ["Identifier"], checkPath: function checkPath(_ref3) { var node = _ref3.node, parent = _ref3.parent; return t.isIdentifier(node) && t.isBinding(node, parent); } }; var Statement = exports.Statement = { types: ["Statement"], checkPath: function checkPath(_ref4) { var node = _ref4.node, parent = _ref4.parent; if (t.isStatement(node)) { if (t.isVariableDeclaration(node)) { if (t.isForXStatement(parent, { left: node })) return false; if (t.isForStatement(parent, { init: node })) return false; } return true; } else { return false; } } }; var Expression = exports.Expression = { types: ["Expression"], checkPath: function checkPath(path) { if (path.isIdentifier()) { return path.isReferencedIdentifier(); } else { return t.isExpression(path.node); } } }; var Scope = exports.Scope = { types: ["Scopable"], checkPath: function checkPath(path) { return t.isScope(path.node, path.parent); } }; var Referenced = exports.Referenced = { checkPath: function checkPath(path) { return t.isReferenced(path.node, path.parent); } }; var BlockScoped = exports.BlockScoped = { checkPath: function checkPath(path) { return t.isBlockScoped(path.node); } }; var Var = exports.Var = { types: ["VariableDeclaration"], checkPath: function checkPath(path) { return t.isVar(path.node); } }; var User = exports.User = { checkPath: function checkPath(path) { return path.node && !!path.node.loc; } }; var Generated = exports.Generated = { checkPath: function checkPath(path) { return !path.isUser(); } }; var Pure = exports.Pure = { checkPath: function checkPath(path, opts) { return path.scope.isPure(path.node, opts); } }; var Flow = exports.Flow = { types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], checkPath: function checkPath(_ref5) { var node = _ref5.node; if (t.isFlow(node)) { return true; } else if (t.isImportDeclaration(node)) { return node.importKind === "type" || node.importKind === "typeof"; } else if (t.isExportDeclaration(node)) { return node.exportKind === "type"; } else if (t.isImportSpecifier(node)) { return node.importKind === "type" || node.importKind === "typeof"; } else { return false; } } };
node_modules/react-icons/md/phone-missed.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdPhoneMissed = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m39.5 27.8c0.3 0.3 0.5 0.7 0.5 1.2s-0.2 0.8-0.5 1.2l-4.1 4.1c-0.3 0.3-0.7 0.5-1.2 0.5s-0.8-0.2-1.2-0.5c-1.3-1.3-2.8-2.3-4.4-3.1-0.6-0.3-0.9-0.9-0.9-1.5v-5.2c-2.5-0.8-5-1.1-7.7-1.1s-5.2 0.3-7.7 1.1v5.2c0 0.7-0.3 1.3-0.9 1.6-1.6 0.7-3.1 1.7-4.4 3-0.4 0.3-0.7 0.5-1.2 0.5s-0.9-0.2-1.2-0.5l-4.1-4.1c-0.3-0.4-0.5-0.7-0.5-1.2s0.2-0.9 0.5-1.2c5.1-4.8 11.9-7.8 19.5-7.8s14.5 3 19.5 7.8z m-28.6-18.7v5.9h-2.5v-10h10v2.5h-5.9l7.5 7.5 10-10 1.6 1.6-11.6 11.8z"/></g> </Icon> ) export default MdPhoneMissed
app/containers/Game/LocationsPopup.js
adrianocola/spyfall
import React from 'react'; import { css } from 'emotion'; import { Modal, ModalBody, ModalHeader } from 'reactstrap'; import { useGameLocations } from 'selectors/gameLocations'; import Locations from 'components/Locations/Locations'; import Localized from 'components/Localized/Localized'; export const LocationsPopup = ({ isOpen, toggle }) => { const gameLocations = useGameLocations(); return ( <Modal centered isOpen={isOpen} toggle={toggle}> <ModalHeader tag="h3" toggle={toggle} className={`${styles.header} justify-content-center`} close={<button type="button" className="close" onClick={toggle}>&times;</button>}> <Localized name="interface.game_locations" /> </ModalHeader> <ModalBody className={styles.body}> <Locations locations={gameLocations} /> </ModalBody> </Modal> ); }; const styles = { header: css({ borderBottom: 'none', }), body: css({ marginBottom: 20, }), }; export default React.memo(LocationsPopup);
app/components/AddFile/index.js
cerebral/cerebral-reference-app
import React from 'react'; import styles from './styles.css'; import icons from 'common/icons.css'; import ToolbarButton from 'common/components/ToolbarButton'; function AddFile(props) { const onAddFileInputChange = (event) => { const fileName = event.target.value; props.onFileNameChange({fileName: fileName}); }; const onAddFileInputKeyDown = (e) => { const keyCode = e.keyCode; if (keyCode === 27) { // Escape props.onAddFileAborted(); } }; const onSubmit = (e) => { e.preventDefault(); props.onFileSubmit(); }; return ( props.showInput ? <div className={styles.wrapper}> <div className={styles.inputWrapper}> <form onSubmit={onSubmit}> <input value={props.value} onChange={onAddFileInputChange} onKeyDown={onAddFileInputKeyDown} className={styles.input} autoFocus placeholder={props.placeholder} onBlur={() => props.onAddFileAborted()}> </input> </form> </div> </div> : <div className={styles.addFileWrapper}> <ToolbarButton icon={icons.addFile} onClick={() => props.onAddFileClick()}/> </div> ); } export default AddFile;
template/src/main.js
yang302/react-cli
import React from 'react' import ReactDOM from 'react-dom' import App from './App' import { AppContainer } from 'react-hot-loader' {{#redux}} import { Provider } from 'react-redux' import store from '$redux/store' {{/redux}} const render = Component => { ReactDOM.render( <AppContainer> {{#if redux}} <Provider store={store}> <Component /> </Provider> {{else}} <Component /> {{/if}} </AppContainer>, document.getElementById('root') ) } render(App) if (module.hot) { module.hot.accept('./App', () => render(App)) }
techCurriculum/ui/solutions/2.3/src/App.js
AnxChow/EngineeringEssentials-group
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; import Title from './components/Title'; function App() { return ( <div> <Title /> </div> ); } export default App;
docs/v5/layouts/src/Home.js
Bandwidth/shared-components
import React from 'react'; import { H1, P, Spacing, Code, Anchor } from '@bandwidth/shared-components'; export default () => ( <Spacing> <H1>Bandwidth Layouts</H1> <P> You've found the documentation for Bandwidth's React layout library. Use the navigation above to get started. </P> <P> This documentation is built with the library itself, plus{' '} <Code>@bandwidth/shared-components</Code>. You can see the code{' '} <Anchor to="https://github.com/Bandwidth/layout" newTab> here </Anchor>. </P> </Spacing> );
test/FactoriesSpec.js
andrew-d/react-bootstrap
import React from 'react'; import components from '../tools/public-components'; let props = { ButtonInput: {value: 'button'}, Glyphicon: {glyph: 'star'}, Modal: {onHide() {}}, ModalTrigger: {modal: React.DOM.div(null)}, OverlayTrigger: {overlay: React.DOM.div(null)} }; function createTest(component) { let factory = require(`../lib/factories/${component}`); describe('factories', function () { it(`Should have a ${component} factory`, function () { assert.ok(React.isValidElement(factory(props[component]))); }); }); } components.map(component => createTest(component));
src/pages/mosaique.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Mosaique' /> )
example/src/screens/types/LightBox.js
eeynard/react-native-navigation
import React from 'react'; import {StyleSheet, View, Text, Dimensions, Button} from 'react-native'; class Lightbox extends React.Component { render() { return ( <View style={styles.container}> <View style={{flex: 8}}> <Text style={styles.title}>{this.props.title}</Text> <Text style={styles.content}>{this.props.content}</Text> </View> <View style={{flex: 2}}> <Button title={'Close'} onPress={() => this.props.onClose()} /> </View> </View> ); } } const styles = StyleSheet.create({ container: { width: Dimensions.get('window').width * 0.7, height: Dimensions.get('window').height * 0.3, backgroundColor: '#ffffff', borderRadius: 5, padding: 16, }, title: { fontSize: 17, fontWeight: '700', }, content: { marginTop: 8, }, }); export default Lightbox;
docs/src/app/components/pages/components/IconButton/ExampleSize.js
rhaedes/material-ui
import React from 'react'; import IconButton from 'material-ui/IconButton'; import ActionHome from 'material-ui/svg-icons/action/home'; const styles = { smallIcon: { width: 36, height: 36, }, mediumIcon: { width: 48, height: 48, }, largeIcon: { width: 60, height: 60, }, small: { width: 72, height: 72, padding: 16, }, medium: { width: 96, height: 96, padding: 24, }, large: { width: 120, height: 120, padding: 30, }, }; const IconButtonExampleSize = () => ( <div> <IconButton> <ActionHome /> </IconButton> <IconButton iconStyle={styles.smallIcon} style={styles.small} > <ActionHome /> </IconButton> <IconButton iconStyle={styles.mediumIcon} style={styles.medium} > <ActionHome /> </IconButton> <IconButton iconStyle={styles.largeIcon} style={styles.large} > <ActionHome /> </IconButton> </div> ); export default IconButtonExampleSize;
redux-weather-forecast/src/components/app.js
andreassiegel/react-redux
import React, { Component } from 'react'; import SearchBar from '../containers/search-bar'; import WeatherList from '../containers/weather_list'; export default class App extends Component { render() { return ( <div> <SearchBar /> <WeatherList /> </div> ); } }
stories/props/toolbar.stories.js
jquense/react-big-calendar
import React from 'react' import moment from 'moment' import { Calendar, momentLocalizer } from '../../src' import demoEvents from '../resources/events' import mdx from './toolbar.mdx' const mLocalizer = momentLocalizer(moment) export default { title: 'props', component: Calendar, argTypes: { localizer: { control: { type: null } }, events: { control: { type: null } }, defaultDate: { control: { type: null, }, }, toolbar: 'boolean', }, parameters: { docs: { page: mdx, }, }, } const Template = (args) => ( <div className="height600"> <Calendar {...args} /> </div> ) export const Toolbar = Template.bind({}) Toolbar.storyName = 'toolbar' Toolbar.args = { defaultDate: new Date(2015, 3, 13), events: demoEvents, localizer: mLocalizer, toolbar: true, }
src/svg-icons/action/schedule.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSchedule = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/> </SvgIcon> ); ActionSchedule = pure(ActionSchedule); ActionSchedule.displayName = 'ActionSchedule'; export default ActionSchedule;
examples/universal/server/server.js
neighborhood999/redux
/* eslint-disable no-console, no-use-before-define */ import path from 'path' import Express from 'express' import qs from 'qs' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import webpackConfig from '../webpack.config' import React from 'react' import { renderToString } from 'react-dom/server' import { Provider } from 'react-redux' import configureStore from '../common/store/configureStore' import App from '../common/containers/App' import { fetchCounter } from '../common/api/counter' const app = new Express() const port = 3000 // Use this middleware to set up hot module reloading via webpack. const compiler = webpack(webpackConfig) app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })) app.use(webpackHotMiddleware(compiler)) // This is fired every time the server side receives a request app.use(handleRender) function handleRender(req, res) { // Query our mock API asynchronously fetchCounter(apiResult => { // Read the counter from the request, if provided const params = qs.parse(req.query) const counter = parseInt(params.counter, 10) || apiResult || 0 // Compile an initial state const initialState = { counter } // Create a new Redux store instance const store = configureStore(initialState) // Render the component to a string const html = renderToString( <Provider store={store}> <App /> </Provider> ) // Grab the initial state from our Redux store const finalState = store.getState() // Send the rendered page back to the client res.send(renderFullPage(html, finalState)) }) } function renderFullPage(html, initialState) { return ` <!doctype html> <html> <head> <title>Redux Universal Example</title> </head> <body> <div id="app">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)} </script> <script src="/static/bundle.js"></script> </body> </html> ` } app.listen(port, (error) => { if (error) { console.error(error) } else { console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`) } })
src/components/Nodes/component.js
fhelwanger/bayesjs-editor
import React from 'react'; import Node from 'components/Node'; const Nodes = ({ nodes, onMouseDown, onDoubleClick, onStateDoubleClick, contextItems, }) => nodes.map((node) => { const props = { ...node, onMouseDown: onMouseDown(node), onDoubleClick: onDoubleClick(node), onStateDoubleClick: onStateDoubleClick(node), }; return <Node key={node.id} contextItems={contextItems} {...props} />; }); export default Nodes;
polyfill-service-web/app/components/VersionsSupport/index.js
reiniergs/polyfill-service
import React from 'react'; import './styles.scss'; const StatusClass = { 0: 'missing', 1: 'polyfilled', 2: 'native' }; function sortNumStrings(arr) { return arr.sort((a, b) => Number(a) - Number(b)); } export default ({ data }) => ( <div> {sortNumStrings(Object.keys(data)).map(version => <span className={'status-' + StatusClass[data[version]]}>{version}</span> )} </div> )
src/svg-icons/device/signal-cellular-connected-no-internet-0-bar.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet0Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 22h2v-2h-2v2zm0-12v8h2v-8h-2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet0Bar = pure(DeviceSignalCellularConnectedNoInternet0Bar); DeviceSignalCellularConnectedNoInternet0Bar.displayName = 'DeviceSignalCellularConnectedNoInternet0Bar'; DeviceSignalCellularConnectedNoInternet0Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet0Bar;
ajax/libs/cssx/2.0.0/cssxler.min.js
sashberd/cdnjs
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("cssxler",[],e):"object"==typeof exports?exports.cssxler=e():t.cssxler=e()}(this,function(){return function(t){function e(i){if(s[i])return s[i].exports;var r=s[i]={exports:{},id:i,loaded:!1};return t[i].call(r.exports,r,r.exports,e),r.loaded=!0,r.exports}var s={};return e.m=t,e.c=s,e.p="",e(0)}([function(t,e,s){var i=s(1),r=s(3),n=s(5)["default"],a=s(386),o=s(387),u={CSSXDefinition:s(388),CSSXElement:s(391),CSSXProperty:s(392),CSSXRule:s(394),CSSXRules:s(395),CSSXSelector:s(396),CSSXValue:s(397),CSSXMediaQueryElement:s(398)};t.exports=function(t,e){var s=i(t);return r(s.program,u),n(s,a({minified:!1,compact:!1,concise:!1,quotes:"single",sourceMaps:!1},e||{}),t).code},t.exports.ast=i,t.exports.reset=function(){o.resetIDs()}},function(t,e,s){var i=s(2),r=["jsx","cssx","flow","asyncFunctions","classConstructorCall","doExpressions","trailingFunctionCommas","objectRestSpread","decorators","classProperties","exportExtensions","exponentiationOperator","asyncGenerators","functionBind","functionSent"];t.exports=function(t){return i.parse(t,{plugins:r})}},function(t,e,s){var i,i;!function(e){t.exports=e()}(function(){return function t(e,s,r){function n(o,u){if(!s[o]){if(!e[o]){var p="function"==typeof i&&i;if(!u&&p)return i(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=s[o]={exports:{}};e[o][0].call(l.exports,function(t){var s=e[o][1][t];return n(s?s:t)},l,l.exports,t,e,s,r)}return s[o].exports}for(var a="function"==typeof i&&i,o=0;o<r.length;o++)n(r[o]);return n}({1:[function(t,e,s){"use strict";function i(t,e){return new a["default"](e,t).parse()}var r=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0,s.parse=i;var n=t("./parser"),a=r(n);t("./parser/util"),t("./parser/statement"),t("./parser/lval"),t("./parser/expression"),t("./parser/node"),t("./parser/location"),t("./parser/comments");var o=t("./tokenizer/types");t("./tokenizer"),t("./tokenizer/context");var u=t("./plugins/flow"),p=r(u),c=t("./plugins/jsx"),l=r(c),h=t("./plugins/cssx"),f=r(h);n.plugins.flow=p["default"],n.plugins.jsx=l["default"],n.plugins.cssx=f["default"],s.tokTypes=o.types},{"./parser":5,"./parser/comments":3,"./parser/expression":4,"./parser/location":6,"./parser/lval":7,"./parser/node":8,"./parser/statement":9,"./parser/util":10,"./plugins/cssx":14,"./plugins/flow":20,"./plugins/jsx":21,"./tokenizer":24,"./tokenizer/context":23,"./tokenizer/types":26,"babel-runtime/helpers/interop-require-default":35}],2:[function(t,e,s){"use strict";function i(t){var e={};for(var s in r)e[s]=t&&s in t?t[s]:r[s];return e}s.__esModule=!0,s.getOptions=i;var r={sourceType:"script",allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,plugins:[],strictMode:null};s.defaultOptions=r},{}],3:[function(t,e,s){"use strict";function i(t){return t[t.length-1]}var r=t("babel-runtime/helpers/interop-require-default")["default"],n=t("./index"),a=r(n),o=a["default"].prototype;o.addComment=function(t){this.state.trailingComments.push(t),this.state.leadingComments.push(t)},o.processComment=function(t){if(!("Program"===t.type&&t.body.length>0)){var e=this.state.commentStack,s=void 0,r=void 0,n=void 0;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=t.end?(r=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else{var a=i(e);e.length>0&&a.trailingComments&&a.trailingComments[0].start>=t.end&&(r=a.trailingComments,a.trailingComments=null)}for(;e.length>0&&i(e).start>=t.start;)s=e.pop();if(s){if(s.leadingComments)if(s!==t&&i(s.leadingComments).end<=t.start)t.leadingComments=s.leadingComments,s.leadingComments=null;else for(n=s.leadingComments.length-2;n>=0;--n)if(s.leadingComments[n].end<=t.start){t.leadingComments=s.leadingComments.splice(0,n+1);break}}else if(this.state.leadingComments.length>0)if(i(this.state.leadingComments).end<=t.start)t.leadingComments=this.state.leadingComments,this.state.leadingComments=[];else{for(n=0;n<this.state.leadingComments.length&&!(this.state.leadingComments[n].end>t.start);n++);t.leadingComments=this.state.leadingComments.slice(0,n),0===t.leadingComments.length&&(t.leadingComments=null),r=this.state.leadingComments.slice(n),0===r.length&&(r=null)}r&&(r.length&&r[0].start>=t.start&&i(r).end<=t.end?t.innerComments=r:t.trailingComments=r),e.push(t)}}},{"./index":5,"babel-runtime/helpers/interop-require-default":35}],4:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/object/create")["default"],r=t("babel-runtime/core-js/get-iterator")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"],a=t("../tokenizer/types"),o=t("./index"),u=n(o),p=t("../util/identifier"),c=u["default"].prototype;c.checkPropClash=function(t,e){if(!t.computed){var s=t.key,i=void 0;switch(s.type){case"Identifier":i=s.name;break;case"StringLiteral":case"NumericLiteral":i=String(s.value);break;default:return}"__proto__"===i&&"init"===t.kind&&(e.proto&&this.raise(s.start,"Redefinition of __proto__ property"),e.proto=!0)}},c.parseExpression=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.parseMaybeAssign(t,e);if(this.match(a.types.comma)){var n=this.startNodeAt(s,i);for(n.expressions=[r];this.eat(a.types.comma);)n.expressions.push(this.parseMaybeAssign(t,e));return this.toReferencedList(n.expressions),this.finishNode(n,"SequenceExpression")}return r},c.parseMaybeAssign=function(t,e,s){if(this.match(a.types._yield)&&this.state.inGenerator)return this.parseYield();var i=void 0;e?i=!1:(e={start:0},i=!0);var r=this.state.start,n=this.state.startLoc;(this.match(a.types.parenL)||this.match(a.types.name))&&(this.state.potentialArrowAt=this.state.start);var o=this.parseMaybeConditional(t,e);if(s&&(o=s.call(this,o,r,n)),this.state.type.isAssign){var u=this.startNodeAt(r,n);if(u.operator=this.state.value,u.left=this.match(a.types.eq)?this.toAssignable(o):o,e.start=0,this.checkLVal(o),o.extra&&o.extra.parenthesized){var p=void 0;"ObjectPattern"===o.type?p="`({a}) = 0` use `({a} = 0)`":"ArrayPattern"===o.type&&(p="`([a]) = 0` use `([a] = 0)`"),p&&this.raise(o.start,"You're trying to assign to a parenthesized expression, eg. instead of "+p)}return this.next(),u.right=this.parseMaybeAssign(t),this.finishNode(u,"AssignmentExpression")}return i&&e.start&&this.unexpected(e.start),o},c.parseMaybeConditional=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.parseExprOps(t,e);if(e&&e.start)return r;if(this.eat(a.types.question)){var n=this.startNodeAt(s,i);return n.test=r,n.consequent=this.parseMaybeAssign(),this.expect(a.types.colon),n.alternate=this.parseMaybeAssign(t),this.finishNode(n,"ConditionalExpression")}return r},c.parseExprOps=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.parseMaybeUnary(e);return e&&e.start?r:this.parseExprOp(r,s,i,-1,t)},c.parseExprOp=function(t,e,s,i,r){var n=this.state.type.binop;if(!(null==n||r&&this.match(a.types._in))&&n>i){var o=this.startNodeAt(e,s);o.left=t,o.operator=this.state.value,"**"===o.operator&&"UnaryExpression"===t.type&&t.extra&&!t.extra.parenthesizedArgument&&this.raise(t.argument.start,"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");var u=this.state.type;this.next();var p=this.state.start,c=this.state.startLoc;return o.right=this.parseExprOp(this.parseMaybeUnary(),p,c,u.rightAssociative?n-1:n,r),this.finishNode(o,u===a.types.logicalOR||u===a.types.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(o,e,s,i,r)}return t},c.parseMaybeUnary=function(t){if(this.state.type.prefix){var e=this.startNode(),s=this.match(a.types.incDec);e.operator=this.state.value,e.prefix=!0,this.next();var i=this.state.type;return this.addExtra(e,"parenthesizedArgument",i===a.types.parenL),e.argument=this.parseMaybeUnary(),t&&t.start&&this.unexpected(t.start),s?this.checkLVal(e.argument):this.state.strict&&"delete"===e.operator&&"Identifier"===e.argument.type&&this.raise(e.start,"Deleting local variable in strict mode"),this.finishNode(e,s?"UpdateExpression":"UnaryExpression")}var r=this.state.start,n=this.state.startLoc,o=this.parseExprSubscripts(t);if(t&&t.start)return o;for(;this.state.type.postfix&&!this.canInsertSemicolon();){var e=this.startNodeAt(r,n);e.operator=this.state.value,e.prefix=!1,e.argument=o,this.checkLVal(o),this.next(),o=this.finishNode(e,"UpdateExpression")}return o},c.parseExprSubscripts=function(t){var e=this.state.start,s=this.state.startLoc,i=this.state.potentialArrowAt,r=this.parseExprAtom(t);return"ArrowFunctionExpression"===r.type&&r.start===i?r:t&&t.start?r:this.parseSubscripts(r,e,s)},c.parseSubscripts=function(t,e,s,i){for(;;){if(!i&&this.eat(a.types.doubleColon)){var r=this.startNodeAt(e,s);return r.object=t,r.callee=this.parseNoCallExpr(),this.parseSubscripts(this.finishNode(r,"BindExpression"),e,s,i)}if(this.eat(a.types.dot)){var r=this.startNodeAt(e,s);r.object=t,r.property=this.parseIdentifier(!0),r.computed=!1,t=this.finishNode(r,"MemberExpression")}else if(this.eat(a.types.bracketL)){var r=this.startNodeAt(e,s);r.object=t,r.property=this.parseExpression(),r.computed=!0,this.expect(a.types.bracketR),t=this.finishNode(r,"MemberExpression")}else if(!i&&this.match(a.types.parenL)){var n=this.state.potentialArrowAt===t.start&&"Identifier"===t.type&&"async"===t.name&&!this.canInsertSemicolon();this.next();var r=this.startNodeAt(e,s);if(r.callee=t,r.arguments=this.parseCallExpressionArguments(a.types.parenR,this.hasPlugin("trailingFunctionCommas"),n),t=this.finishNode(r,"CallExpression"),n&&this.shouldParseAsyncArrow())return this.parseAsyncArrowFromCallExpression(this.startNodeAt(e,s),r);this.toReferencedList(r.arguments)}else{if(!this.match(a.types.backQuote))return t;var r=this.startNodeAt(e,s);r.tag=t,r.quasi=this.parseTemplate(),t=this.finishNode(r,"TaggedTemplateExpression")}}},c.parseCallExpressionArguments=function(t,e,s){for(var i=void 0,r=[],n=!0;!this.eat(t);){if(n)n=!1;else if(this.expect(a.types.comma),e&&this.eat(t))break;this.match(a.types.parenL)&&!i&&(i=this.state.start),r.push(this.parseExprListItem())}return s&&i&&this.shouldParseAsyncArrow()&&this.unexpected(),r},c.shouldParseAsyncArrow=function(){return this.match(a.types.arrow)},c.parseAsyncArrowFromCallExpression=function(t,e){return this.hasPlugin("asyncFunctions")||this.unexpected(),this.expect(a.types.arrow),this.parseArrowExpression(t,e.arguments,!0)},c.parseNoCallExpr=function(){var t=this.state.start,e=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,e,!0)},c.parseExprAtom=function(t){var e=void 0,s=this.state.potentialArrowAt===this.state.start;switch(this.state.type){case a.types._super:return this.state.inMethod||this.options.allowSuperOutsideMethod||this.raise(this.state.start,"'super' outside of function or class"),e=this.startNode(),this.next(),this.match(a.types.parenL)||this.match(a.types.bracketL)||this.match(a.types.dot)||this.unexpected(),this.match(a.types.parenL)&&"constructor"!==this.state.inMethod&&!this.options.allowSuperOutsideMethod&&this.raise(e.start,"super() outside of class constructor"),this.finishNode(e,"Super");case a.types._this:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case a.types._yield:this.state.inGenerator&&this.unexpected();case a.types.name:e=this.startNode();var i=this.hasPlugin("asyncFunctions")&&"await"===this.state.value&&this.state.inAsync,r=this.shouldAllowYieldIdentifier(),n=this.parseIdentifier(i||r);if(this.hasPlugin("asyncFunctions"))if("await"===n.name){if(this.state.inAsync||this.inModule)return this.parseAwait(e)}else{if("async"===n.name&&this.match(a.types._function)&&!this.canInsertSemicolon())return this.next(),this.parseFunction(e,!1,!1,!0);if(s&&"async"===n.name&&this.match(a.types.name)){var o=[this.parseIdentifier()];return this.expect(a.types.arrow),this.parseArrowExpression(e,o,!0)}}return s&&!this.canInsertSemicolon()&&this.eat(a.types.arrow)?this.parseArrowExpression(e,[n]):n;case a.types._do:if(this.hasPlugin("doExpressions")){var u=this.startNode();this.next();var p=this.state.inFunction,c=this.state.labels;return this.state.labels=[],this.state.inFunction=!1,u.body=this.parseBlock(!1,!0),this.state.inFunction=p,this.state.labels=c,this.finishNode(u,"DoExpression")}case a.types.regexp:var l=this.state.value;return e=this.parseLiteral(l.value,"RegExpLiteral"),e.pattern=l.pattern,e.flags=l.flags,e;case a.types.num:return this.parseLiteral(this.state.value,"NumericLiteral");case a.types.string:return this.parseLiteral(this.state.value,"StringLiteral");case a.types._null:return e=this.startNode(),this.next(),this.finishNode(e,"NullLiteral");case a.types._true:case a.types._false:return e=this.startNode(),e.value=this.match(a.types._true),this.next(),this.finishNode(e,"BooleanLiteral");case a.types.parenL:return this.parseParenAndDistinguishExpression(null,null,s);case a.types.bracketL:return e=this.startNode(),this.next(),e.elements=this.parseExprList(a.types.bracketR,!0,!0,t),this.toReferencedList(e.elements),this.finishNode(e,"ArrayExpression");case a.types.braceL:return this.parseObj(!1,t);case a.types._function:return this.parseFunctionExpression();case a.types.at:this.parseDecorators();case a.types._class:return e=this.startNode(),this.takeDecorators(e),this.parseClass(e,!1);case a.types._new:return this.parseNew();case a.types.backQuote:return this.parseTemplate();case a.types.doubleColon:e=this.startNode(),this.next(),e.object=null;var h=e.callee=this.parseNoCallExpr();if("MemberExpression"===h.type)return this.finishNode(e,"BindExpression");this.raise(h.start,"Binding should be performed on object property.");default:this.unexpected()}},c.parseFunctionExpression=function(){var t=this.startNode(),e=this.parseIdentifier(!0);return this.state.inGenerator&&this.eat(a.types.dot)&&this.hasPlugin("functionSent")?this.parseMetaProperty(t,e,"sent"):this.parseFunction(t,!1)},c.parseMetaProperty=function(t,e,s){return t.meta=e,t.property=this.parseIdentifier(!0),t.property.name!==s&&this.raise(t.property.start,"The only valid meta property for new is "+e.name+"."+s),this.finishNode(t,"MetaProperty")},c.parseLiteral=function(t,e){var s=this.startNode();return this.addExtra(s,"rawValue",t),this.addExtra(s,"raw",this.input.slice(this.state.start,this.state.end)),s.value=t,this.next(),this.finishNode(s,e)},c.parseParenExpression=function(){this.expect(a.types.parenL);var t=this.parseExpression();return this.expect(a.types.parenR),t},c.parseParenAndDistinguishExpression=function(t,e,s,i){t=t||this.state.start,e=e||this.state.startLoc;var r=void 0;this.next();for(var n=this.state.start,o=this.state.startLoc,u=[],p=!0,c={start:0},l=void 0,h=void 0;!this.match(a.types.parenR);){if(p)p=!1;else if(this.expect(a.types.comma),this.match(a.types.parenR)&&this.hasPlugin("trailingFunctionCommas")){h=this.state.start;break}if(this.match(a.types.ellipsis)){var f=this.state.start,d=this.state.startLoc;l=this.state.start,u.push(this.parseParenItem(this.parseRest(),d,f));break}u.push(this.parseMaybeAssign(!1,c,this.parseParenItem))}var y=this.state.start,m=this.state.startLoc;if(this.expect(a.types.parenR),s&&!this.canInsertSemicolon()&&this.eat(a.types.arrow)){for(var v=0;v<u.length;v++){var g=u[v];g.extra&&g.extra.parenthesized&&this.unexpected(g.extra.parenStart)}return this.parseArrowExpression(this.startNodeAt(t,e),u,i)}if(!u.length){if(i)return;this.unexpected(this.state.lastTokStart)}return h&&this.unexpected(h),l&&this.unexpected(l),c.start&&this.unexpected(c.start),u.length>1?(r=this.startNodeAt(n,o),r.expressions=u,this.toReferencedList(r.expressions),this.finishNodeAt(r,"SequenceExpression",y,m)):r=u[0],this.addExtra(r,"parenthesized",!0),this.addExtra(r,"parenStart",t),r},c.parseParenItem=function(t){return t},c.parseNew=function(){var t=this.startNode(),e=this.parseIdentifier(!0);return this.eat(a.types.dot)?this.parseMetaProperty(t,e,"target"):(t.callee=this.parseNoCallExpr(),this.eat(a.types.parenL)?(t.arguments=this.parseExprList(a.types.parenR,this.hasPlugin("trailingFunctionCommas")),this.toReferencedList(t.arguments)):t.arguments=[],this.finishNode(t,"NewExpression"))},c.parseTemplateElement=function(){var t=this.startNode();return t.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),t.tail=this.match(a.types.backQuote),this.finishNode(t,"TemplateElement")},c.parseTemplate=function(){var t=this.startNode();this.next(),t.expressions=[];var e=this.parseTemplateElement();for(t.quasis=[e];!e.tail;)this.expect(a.types.dollarBraceL),t.expressions.push(this.parseExpression()),this.expect(a.types.braceR),t.quasis.push(e=this.parseTemplateElement());return this.next(),this.finishNode(t,"TemplateLiteral")},c.parseObj=function(t,e){var s=[],r=i(null),n=!0,o=this.startNode();for(o.properties=[],this.next();!this.eat(a.types.braceR);){if(n)n=!1;else if(this.expect(a.types.comma),this.eat(a.types.braceR))break;for(;this.match(a.types.at);)s.push(this.parseDecorator());var u=this.startNode(),p=!1,c=!1,l=void 0,h=void 0;if(s.length&&(u.decorators=s,s=[]),this.hasPlugin("objectRestSpread")&&this.match(a.types.ellipsis))u=this.parseSpread(),u.type=t?"RestProperty":"SpreadProperty",o.properties.push(u);else{if(u.method=!1,u.shorthand=!1,(t||e)&&(l=this.state.start,h=this.state.startLoc),t||(p=this.eat(a.types.star)),!t&&this.hasPlugin("asyncFunctions")&&this.isContextual("async")){p&&this.unexpected();var f=this.parseIdentifier();this.match(a.types.colon)||this.match(a.types.parenL)||this.match(a.types.braceR)?u.key=f:(c=!0,this.hasPlugin("asyncGenerators")&&(p=this.eat(a.types.star)),this.parsePropertyName(u))}else this.parsePropertyName(u);this.parseObjPropValue(u,l,h,p,c,t,e),this.checkPropClash(u,r),u.shorthand&&this.addExtra(u,"shorthand",!0),o.properties.push(u)}}return s.length&&this.raise(this.state.start,"You have trailing decorators with no property"),this.finishNode(o,t?"ObjectPattern":"ObjectExpression")},c.parseObjPropValue=function(t,e,s,i,r,n,o){if(r||i||this.match(a.types.parenL))return n&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,i,r),this.finishNode(t,"ObjectMethod");if(this.eat(a.types.colon))return t.value=n?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,o),this.finishNode(t,"ObjectProperty");if(!(t.computed||"Identifier"!==t.key.type||"get"!==t.key.name&&"set"!==t.key.name||this.match(a.types.comma)||this.match(a.types.braceR))){(i||r||n)&&this.unexpected(),t.kind=t.key.name,this.parsePropertyName(t),this.parseMethod(t,!1);var u="get"===t.kind?0:1;if(t.params.length!==u){var c=t.start;"get"===t.kind?this.raise(c,"getter should have no params"):this.raise(c,"setter should have exactly one param")}return this.finishNode(t,"ObjectMethod")}if(!t.computed&&"Identifier"===t.key.type){if(n){var l=this.isKeyword(t.key.name);!l&&this.state.strict&&(l=p.reservedWords.strictBind(t.key.name)||p.reservedWords.strict(t.key.name)),l&&this.raise(t.key.start,"Binding "+t.key.name),t.value=this.parseMaybeDefault(e,s,t.key.__clone())}else this.match(a.types.eq)&&o?(o.start||(o.start=this.state.start),t.value=this.parseMaybeDefault(e,s,t.key.__clone())):t.value=t.key.__clone();return t.shorthand=!0,this.finishNode(t,"ObjectProperty")}this.unexpected()},c.parsePropertyName=function(t){return this.eat(a.types.bracketL)?(t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(a.types.bracketR),t.key):(t.computed=!1,t.key=this.match(a.types.num)||this.match(a.types.string)?this.parseExprAtom():this.parseIdentifier(!0))},c.initFunction=function(t,e){t.id=null,t.generator=!1,t.expression=!1,this.hasPlugin("asyncFunctions")&&(t.async=!!e)},c.parseMethod=function(t,e,s){var i=this.state.inMethod;return this.state.inMethod=t.kind||!0,this.initFunction(t,s),this.expect(a.types.parenL),t.params=this.parseBindingList(a.types.parenR,!1,this.hasPlugin("trailingFunctionCommas")),t.generator=e,this.parseFunctionBody(t),this.state.inMethod=i,t},c.parseArrowExpression=function(t,e,s){return this.initFunction(t,s),t.params=this.toAssignableList(e,!0),this.parseFunctionBody(t,!0),this.finishNode(t,"ArrowFunctionExpression")},c.parseFunctionBody=function(t,e){var s=e&&!this.match(a.types.braceL),n=this.state.inAsync;if(this.state.inAsync=t.async,s)t.body=this.parseMaybeAssign(),t.expression=!0;else{var o=this.state.inFunction,u=this.state.inGenerator,p=this.state.labels;this.state.inFunction=!0,this.state.inGenerator=t.generator,this.state.labels=[],t.body=this.parseBlock(!0),t.expression=!1,this.state.inFunction=o,this.state.inGenerator=u,this.state.labels=p}this.state.inAsync=n;var c=this.state.strict,l=!1,h=!1;if(e&&(c=!0),!s&&t.body.directives.length)for(var f=t.body.directives,d=Array.isArray(f),y=0,f=d?f:r(f);;){var m;if(d){if(y>=f.length)break;m=f[y++]}else{if(y=f.next(),y.done)break;m=y.value}var v=m;if("use strict"===v.value.value){h=!0,c=!0,l=!0;break}}if(h&&t.id&&"Identifier"===t.id.type&&"yield"===t.id.name&&this.raise(t.id.start,"Binding yield in strict mode"),c){var g=i(null),x=this.state.strict;l&&(this.state.strict=!0),t.id&&this.checkLVal(t.id,!0);for(var A=t.params,b=Array.isArray(A),E=0,A=b?A:r(A);;){var C;if(b){if(E>=A.length)break;C=A[E++]}else{if(E=A.next(),E.done)break;C=E.value}var D=C;this.checkLVal(D,!0,g)}this.state.strict=x}},c.parseExprList=function(t,e,s,i){for(var r=[],n=!0;!this.eat(t);){if(n)n=!1;else if(this.expect(a.types.comma),e&&this.eat(t))break;r.push(this.parseExprListItem(s,i))}return r},c.parseExprListItem=function(t,e){var s=void 0;return s=t&&this.match(a.types.comma)?null:this.match(a.types.ellipsis)?this.parseSpread(e):this.parseMaybeAssign(!1,e)},c.parseIdentifier=function(t){var e=this.startNode();return this.match(a.types.name)?(!t&&this.state.strict&&p.reservedWords.strict(this.state.value)&&this.raise(this.state.start,"The keyword '"+this.state.value+"' is reserved"),e.name=this.state.value):t&&this.state.type.keyword?e.name=this.state.type.keyword:this.unexpected(),!t&&"await"===e.name&&this.state.inAsync&&this.raise(e.start,"invalid use of await inside of an async function"),this.next(),this.finishNode(e,"Identifier")},c.parseAwait=function(t){return this.state.inAsync||this.unexpected(),this.isLineTerminator()&&this.unexpected(),this.match(a.types.star)&&this.raise(t.start,"await* has been removed from the async functions proposal. Use Promise.all() instead."),t.argument=this.parseMaybeUnary(),this.finishNode(t,"AwaitExpression")},c.parseYield=function(){var t=this.startNode();return this.next(),this.match(a.types.semi)||this.canInsertSemicolon()||!this.match(a.types.star)&&!this.state.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(a.types.star),t.argument=this.parseMaybeAssign()),this.finishNode(t,"YieldExpression")}},{"../tokenizer/types":26,"../util/identifier":27,"./index":5,"babel-runtime/core-js/get-iterator":30,"babel-runtime/core-js/object/create":31,"babel-runtime/helpers/interop-require-default":35}],5:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/inherits")["default"],r=t("babel-runtime/helpers/class-call-check")["default"],n=t("babel-runtime/core-js/get-iterator")["default"],a=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var o=t("../util/identifier"),u=t("../options"),p=t("../tokenizer"),c=a(p),l={};s.plugins=l;var h=function(t){function e(s,i){r(this,e),s=u.getOptions(s),t.call(this,s,i),this.options=s,this.inModule="module"===this.options.sourceType,this.isReservedWord=o.reservedWords[6],this.input=i,this.plugins=this.loadPlugins(this.options.plugins),0===this.state.pos&&"#"===this.input[0]&&"!"===this.input[1]&&this.skipLineComment(2)}return i(e,t),e.prototype.hasPlugin=function(t){return!(!this.plugins["*"]&&!this.plugins[t])},e.prototype.extend=function(t,e){this[t]=e(this[t])},e.prototype.loadPlugins=function(t){var e={};t.indexOf("flow")>=0&&(t=t.filter(function(t){return"flow"!==t}),t.push("flow"));for(var i=t,r=Array.isArray(i),a=0,i=r?i:n(i);;){var o;if(r){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;if(!e[u]){e[u]=!0;var p=s.plugins[u];p&&p(this)}}return e},e.prototype.parse=function(){var t=this.startNode(),e=this.startNode();return this.nextToken(),this.parseTopLevel(t,e)},e}(c["default"]);s["default"]=h},{"../options":2,"../tokenizer":24,"../util/identifier":27,"babel-runtime/core-js/get-iterator":30,"babel-runtime/helpers/class-call-check":33,"babel-runtime/helpers/inherits":34,"babel-runtime/helpers/interop-require-default":35}],6:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../util/location"),n=t("./index"),a=i(n),o=a["default"].prototype;o.raise=function(t,e){var s=r.getLineInfo(this.input,t);e+=" ("+s.line+":"+s.column+")";var i=new SyntaxError(e);throw i.pos=t,i.loc=s,i}},{"../util/location":28,"./index":5,"babel-runtime/helpers/interop-require-default":35}],7:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/get-iterator")["default"],r=t("babel-runtime/helpers/interop-require-default")["default"],n=t("../tokenizer/types"),a=t("./index"),o=r(a),u=t("../util/identifier"),p=o["default"].prototype;p.toAssignable=function(t,e){if(t)switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":t.type="ObjectPattern";for(var s=t.properties,r=Array.isArray(s),n=0,s=r?s:i(s);;){var a;if(r){if(n>=s.length)break;a=s[n++]}else{if(n=s.next(),n.done)break;a=n.value}var o=a;"ObjectMethod"===o.type?"get"===o.kind||"set"===o.kind?this.raise(o.key.start,"Object pattern can't contain getter or setter"):this.raise(o.key.start,"Object pattern can't contain methods"):this.toAssignable(o,e)}break;case"ObjectProperty":this.toAssignable(t.value,e);break;case"SpreadProperty":t.type="RestProperty";break;case"ArrayExpression":t.type="ArrayPattern",this.toAssignableList(t.elements,e);break;case"AssignmentExpression":"="===t.operator?(t.type="AssignmentPattern",delete t.operator):this.raise(t.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!e)break;default:this.raise(t.start,"Assigning to rvalue")}return t},p.toAssignableList=function(t,e){var s=t.length;if(s){var i=t[s-1];if(i&&"RestElement"===i.type)--s;else if(i&&"SpreadElement"===i.type){i.type="RestElement";var r=i.argument;this.toAssignable(r,e),"Identifier"!==r.type&&"MemberExpression"!==r.type&&"ArrayPattern"!==r.type&&this.unexpected(r.start),--s}}for(var n=0;s>n;n++){var a=t[n];a&&this.toAssignable(a,e)}return t},p.toReferencedList=function(t){return t},p.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(t),this.finishNode(e,"SpreadElement")},p.parseRest=function(){var t=this.startNode();return this.next(),t.argument=this.parseBindingIdentifier(),this.finishNode(t,"RestElement")},p.shouldAllowYieldIdentifier=function(){return this.match(n.types._yield)&&!this.state.strict&&!this.state.inGenerator},p.parseBindingIdentifier=function(){return this.parseIdentifier(this.shouldAllowYieldIdentifier())},p.parseBindingAtom=function(){switch(this.state.type){case n.types._yield:(this.state.strict||this.state.inGenerator)&&this.unexpected();case n.types.name:return this.parseIdentifier(!0);case n.types.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(n.types.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case n.types.braceL:return this.parseObj(!0);default:this.unexpected()}},p.parseBindingList=function(t,e,s){for(var i=[],r=!0;!this.eat(t);)if(r?r=!1:this.expect(n.types.comma),e&&this.match(n.types.comma))i.push(null);else{if(s&&this.eat(t))break;if(this.match(n.types.ellipsis)){i.push(this.parseAssignableListItemTypes(this.parseRest())),this.expect(t);break}var a=this.parseMaybeDefault();this.parseAssignableListItemTypes(a),i.push(this.parseMaybeDefault(null,null,a))}return i},p.parseAssignableListItemTypes=function(t){return t},p.parseMaybeDefault=function(t,e,s){if(e=e||this.state.startLoc,t=t||this.state.start,s=s||this.parseBindingAtom(),!this.eat(n.types.eq))return s;var i=this.startNodeAt(t,e);return i.left=s,i.right=this.parseMaybeAssign(),this.finishNode(i,"AssignmentPattern")},p.checkLVal=function(t,e,s){switch(t.type){case"Identifier":if(this.state.strict&&(u.reservedWords.strictBind(t.name)||u.reservedWords.strict(t.name))&&this.raise(t.start,(e?"Binding ":"Assigning to ")+t.name+" in strict mode"),s){var r="_"+t.name;s[r]?this.raise(t.start,"Argument name clash in strict mode"):s[r]=!0}break;case"MemberExpression":e&&this.raise(t.start,(e?"Binding":"Assigning to")+" member expression");break;case"ObjectPattern":for(var n=t.properties,a=Array.isArray(n),o=0,n=a?n:i(n);;){var p;if(a){if(o>=n.length)break;p=n[o++]}else{if(o=n.next(),o.done)break;p=o.value}var c=p;"ObjectProperty"===c.type&&(c=c.value),this.checkLVal(c,e,s)}break;case"ArrayPattern":for(var l=t.elements,h=Array.isArray(l),f=0,l=h?l:i(l);;){var d;if(h){if(f>=l.length)break;d=l[f++]}else{if(f=l.next(),f.done)break;d=f.value}var y=d;y&&this.checkLVal(y,e,s)}break;case"AssignmentPattern":this.checkLVal(t.left,e,s);break;case"RestProperty":case"RestElement":this.checkLVal(t.argument,e,s);break;default:this.raise(t.start,(e?"Binding":"Assigning to")+" rvalue")}}},{"../tokenizer/types":26,"../util/identifier":27,"./index":5,"babel-runtime/core-js/get-iterator":30,"babel-runtime/helpers/interop-require-default":35}],8:[function(t,e,s){"use strict";function i(t,e,s,i){return t.type=e,t.end=s,t.loc.end=i,this.processComment(t),t}var r=t("babel-runtime/helpers/class-call-check")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"],a=t("./index"),o=n(a),u=t("../util/location"),p=o["default"].prototype,c=function(){function t(e,s){r(this,t),this.type="",this.start=e,this.end=0,this.loc=new u.SourceLocation(s)}return t.prototype.__clone=function(){var e=new t;for(var s in this)e[s]=this[s];return e},t}();p.startNode=function(){return new c(this.state.start,this.state.startLoc)},p.startNodeAt=function(t,e){return new c(t,e)},p.finishNode=function(t,e){return i.call(this,t,e,this.state.lastTokEnd,this.state.lastTokEndLoc)},p.finishNodeAt=function(t,e,s,r){return i.call(this,t,e,s,r)}},{"../util/location":28,"./index":5,"babel-runtime/helpers/class-call-check":33,"babel-runtime/helpers/interop-require-default":35}],9:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/object/create")["default"],r=t("babel-runtime/core-js/get-iterator")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"],a=t("../tokenizer/types"),o=t("./index"),u=n(o),p=t("../util/whitespace"),c=u["default"].prototype;c.parseTopLevel=function(t,e){return e.sourceType=this.options.sourceType,this.parseBlockBody(e,!0,!0,a.types.eof),t.program=this.finishNode(e,"Program"),t.comments=this.state.comments,t.tokens=this.state.tokens,this.finishNode(t,"File")};var l={kind:"loop"},h={kind:"switch"};c.stmtToDirective=function(t){var e=t.expression,s=this.startNodeAt(e.start,e.loc.start),i=this.startNodeAt(t.start,t.loc.start),r=this.input.slice(e.start,e.end),n=s.value=r.slice(1,-1);return this.addExtra(s,"raw",r),this.addExtra(s,"rawValue",n),i.value=this.finishNodeAt(s,"DirectiveLiteral",e.end,e.loc.end),this.finishNodeAt(i,"Directive",t.end,t.loc.end)},c.parseStatement=function(t,e){this.match(a.types.at)&&this.parseDecorators(!0);var s=this.state.type,i=this.startNode();switch(s){case a.types._break:case a.types._continue:return this.parseBreakContinueStatement(i,s.keyword);case a.types._debugger:return this.parseDebuggerStatement(i);case a.types._do:return this.parseDoStatement(i);case a.types._for:return this.parseForStatement(i);case a.types._function:return t||this.unexpected(),this.parseFunctionStatement(i);case a.types._class:return t||this.unexpected(), this.takeDecorators(i),this.parseClass(i,!0);case a.types._if:return this.parseIfStatement(i);case a.types._return:return this.parseReturnStatement(i);case a.types._switch:return this.parseSwitchStatement(i);case a.types._throw:return this.parseThrowStatement(i);case a.types._try:return this.parseTryStatement(i);case a.types._let:case a.types._const:t||this.unexpected();case a.types._var:return this.parseVarStatement(i,s);case a.types._while:return this.parseWhileStatement(i);case a.types._with:return this.parseWithStatement(i);case a.types.braceL:return this.parseBlock();case a.types.semi:return this.parseEmptyStatement(i);case a.types._export:case a.types._import:return this.options.allowImportExportEverywhere||(e||this.raise(this.state.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.state.start,"'import' and 'export' may appear only with 'sourceType: module'")),s===a.types._import?this.parseImport(i):this.parseExport(i);case a.types.name:if(this.hasPlugin("asyncFunctions")&&"async"===this.state.value){var r=this.state.clone();if(this.next(),this.match(a.types._function)&&!this.canInsertSemicolon())return this.expect(a.types._function),this.parseFunction(i,!0,!1,!0);this.state=r}}var n=this.state.value,o=this.parseExpression();return s===a.types.name&&"Identifier"===o.type&&this.eat(a.types.colon)?this.parseLabeledStatement(i,n,o):this.parseExpressionStatement(i,o)},c.takeDecorators=function(t){this.state.decorators.length&&(t.decorators=this.state.decorators,this.state.decorators=[])},c.parseDecorators=function(t){for(;this.match(a.types.at);)this.state.decorators.push(this.parseDecorator());t&&this.match(a.types._export)||this.match(a.types._class)||this.raise(this.state.start,"Leading decorators must be attached to a class declaration")},c.parseDecorator=function(){this.hasPlugin("decorators")||this.unexpected();var t=this.startNode();return this.next(),t.expression=this.parseMaybeAssign(),this.finishNode(t,"Decorator")},c.parseBreakContinueStatement=function(t,e){var s="break"===e;this.next(),this.isLineTerminator()?t.label=null:this.match(a.types.name)?(t.label=this.parseIdentifier(),this.semicolon()):this.unexpected();var i=void 0;for(i=0;i<this.state.labels.length;++i){var r=this.state.labels[i];if(null==t.label||r.name===t.label.name){if(null!=r.kind&&(s||"loop"===r.kind))break;if(t.label&&s)break}}return i===this.state.labels.length&&this.raise(t.start,"Unsyntactic "+e),this.finishNode(t,s?"BreakStatement":"ContinueStatement")},c.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")},c.parseDoStatement=function(t){return this.next(),this.state.labels.push(l),t.body=this.parseStatement(!1),this.state.labels.pop(),this.expect(a.types._while),t.test=this.parseParenExpression(),this.eat(a.types.semi),this.finishNode(t,"DoWhileStatement")},c.parseForStatement=function(t){if(this.next(),this.state.labels.push(l),this.expect(a.types.parenL),this.match(a.types.semi))return this.parseFor(t,null);if(this.match(a.types._var)||this.match(a.types._let)||this.match(a.types._const)){var e=this.startNode(),s=this.state.type;return this.next(),this.parseVar(e,!0,s),this.finishNode(e,"VariableDeclaration"),!this.match(a.types._in)&&!this.isContextual("of")||1!==e.declarations.length||e.declarations[0].init?this.parseFor(t,e):this.parseForIn(t,e)}var i={start:0},r=this.parseExpression(!0,i);return this.match(a.types._in)||this.isContextual("of")?(this.toAssignable(r),this.checkLVal(r),this.parseForIn(t,r)):(i.start&&this.unexpected(i.start),this.parseFor(t,r))},c.parseFunctionStatement=function(t){return this.next(),this.parseFunction(t,!0)},c.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement(!1),t.alternate=this.eat(a.types._else)?this.parseStatement(!1):null,this.finishNode(t,"IfStatement")},c.parseReturnStatement=function(t){return this.state.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.state.start,"'return' outside of function"),this.next(),this.isLineTerminator()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")},c.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(a.types.braceL),this.state.labels.push(h);for(var e=void 0,s=void 0;!this.match(a.types.braceR);)if(this.match(a.types._case)||this.match(a.types._default)){var i=this.match(a.types._case);e&&this.finishNode(e,"SwitchCase"),t.cases.push(e=this.startNode()),e.consequent=[],this.next(),i?e.test=this.parseExpression():(s&&this.raise(this.state.lastTokStart,"Multiple default clauses"),s=!0,e.test=null),this.expect(a.types.colon)}else e?e.consequent.push(this.parseStatement(!0)):this.unexpected();return e&&this.finishNode(e,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")},c.parseThrowStatement=function(t){return this.next(),p.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.start))&&this.raise(this.state.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")};var f=[];c.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.match(a.types._catch)){var e=this.startNode();this.next(),this.expect(a.types.parenL),e.param=this.parseBindingAtom(),this.checkLVal(e.param,!0,i(null)),this.expect(a.types.parenR),e.body=this.parseBlock(),t.handler=this.finishNode(e,"CatchClause")}return t.guardedHandlers=f,t.finalizer=this.eat(a.types._finally)?this.parseBlock():null,t.handler||t.finalizer||this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")},c.parseVarStatement=function(t,e){return this.next(),this.parseVar(t,!1,e),this.semicolon(),this.finishNode(t,"VariableDeclaration")},c.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.state.labels.push(l),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,"WhileStatement")},c.parseWithStatement=function(t){return this.state.strict&&this.raise(this.state.start,"'with' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement(!1),this.finishNode(t,"WithStatement")},c.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")},c.parseLabeledStatement=function(t,e,s){for(var i=this.state.labels,n=Array.isArray(i),o=0,i=n?i:r(i);;){var u;if(n){if(o>=i.length)break;u=i[o++]}else{if(o=i.next(),o.done)break;u=o.value}var p=u;p.name===e&&this.raise(s.start,"Label '"+e+"' is already declared")}for(var c=this.state.type.isLoop?"loop":this.match(a.types._switch)?"switch":null,l=this.state.labels.length-1;l>=0;l--){var p=this.state.labels[l];if(p.statementStart!==t.start)break;p.statementStart=this.state.start,p.kind=c}return this.state.labels.push({name:e,kind:c,statementStart:this.state.start}),t.body=this.parseStatement(!0),this.state.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")},c.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")},c.parseBlock=function(t){var e=this.startNode();return this.expect(a.types.braceL),this.parseBlockBody(e,t,!1,a.types.braceR),this.finishNode(e,"BlockStatement")},c.parseBlockBody=function(t,e,s,i){t.body=[],t.directives=[];for(var r=!1,n=void 0,a=void 0;!this.eat(i);){r||!this.state.containsOctal||a||(a=this.state.octalPosition);var o=this.parseStatement(!0,s);if(!e||r||"ExpressionStatement"!==o.type||"StringLiteral"!==o.expression.type||o.expression.extra.parenthesized)r=!0,t.body.push(o);else{var u=this.stmtToDirective(o);t.directives.push(u),void 0===n&&"use strict"===u.value.value&&(n=this.state.strict,this.setStrict(!0),a&&this.raise(a,"Octal literal in strict mode"))}}n===!1&&this.setStrict(!1)},c.parseFor=function(t,e){return t.init=e,this.expect(a.types.semi),t.test=this.match(a.types.semi)?null:this.parseExpression(),this.expect(a.types.semi),t.update=this.match(a.types.parenR)?null:this.parseExpression(),this.expect(a.types.parenR),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,"ForStatement")},c.parseForIn=function(t,e){var s=this.match(a.types._in)?"ForInStatement":"ForOfStatement";return this.next(),t.left=e,t.right=this.parseExpression(),this.expect(a.types.parenR),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,s)},c.parseVar=function(t,e,s){for(t.declarations=[],t.kind=s.keyword;;){var i=this.startNode();if(this.parseVarHead(i),this.eat(a.types.eq)?i.init=this.parseMaybeAssign(e):s!==a.types._const||this.match(a.types._in)||this.isContextual("of")?"Identifier"===i.id.type||e&&(this.match(a.types._in)||this.isContextual("of"))?i.init=null:this.raise(this.state.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),t.declarations.push(this.finishNode(i,"VariableDeclarator")),!this.eat(a.types.comma))break}return t},c.parseVarHead=function(t){t.id=this.parseBindingAtom(),this.checkLVal(t.id,!0)},c.parseFunction=function(t,e,s,i,r){var n=this.state.inMethod;return this.state.inMethod=!1,this.initFunction(t,i),this.match(a.types.star)&&(t.async&&!this.hasPlugin("asyncGenerators")?this.unexpected():(t.generator=!0,this.next())),!e||r||this.match(a.types.name)||this.match(a.types._yield)||this.unexpected(),(this.match(a.types.name)||this.match(a.types._yield))&&(t.id=this.parseBindingIdentifier()),this.parseFunctionParams(t),this.parseFunctionBody(t,s),this.state.inMethod=n,this.finishNode(t,e?"FunctionDeclaration":"FunctionExpression")},c.parseFunctionParams=function(t){this.expect(a.types.parenL),t.params=this.parseBindingList(a.types.parenR,!1,this.hasPlugin("trailingFunctionCommas"))},c.parseClass=function(t,e,s){return this.next(),this.parseClassId(t,e,s),this.parseClassSuper(t),this.parseClassBody(t),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")},c.isClassProperty=function(){return this.match(a.types.eq)||this.match(a.types.semi)||this.canInsertSemicolon()},c.parseClassBody=function(t){var e=this.state.strict;this.state.strict=!0;var s=!1,i=!1,r=[],n=this.startNode();for(n.body=[],this.expect(a.types.braceL);!this.eat(a.types.braceR);)if(!this.eat(a.types.semi))if(this.match(a.types.at))r.push(this.parseDecorator());else{var o=this.startNode();r.length&&(o.decorators=r,r=[]);var u=!1,p=this.match(a.types.name)&&"static"===this.state.value,c=this.eat(a.types.star),l=!1,h=!1;if(this.parsePropertyName(o),o["static"]=p&&!this.match(a.types.parenL),o["static"]&&(c&&this.unexpected(),c=this.eat(a.types.star),this.parsePropertyName(o)),!c&&"Identifier"===o.key.type&&!o.computed){if(this.isClassProperty()){n.body.push(this.parseClassProperty(o));continue}this.hasPlugin("classConstructorCall")&&"call"===o.key.name&&this.match(a.types.name)&&"constructor"===this.state.value&&(u=!0,this.parsePropertyName(o))}var f=this.hasPlugin("asyncFunctions")&&!this.match(a.types.parenL)&&!o.computed&&"Identifier"===o.key.type&&"async"===o.key.name;if(f&&(this.hasPlugin("asyncGenerators")&&this.eat(a.types.star)&&(c=!0),h=!0,this.parsePropertyName(o)),o.kind="method",!o.computed){var d=o.key;h||c||"Identifier"!==d.type||this.match(a.types.parenL)||"get"!==d.name&&"set"!==d.name||(l=!0,o.kind=d.name,d=this.parsePropertyName(o));var y=!u&&!o["static"]&&("Identifier"===d.type&&"constructor"===d.name||"StringLiteral"===d.type&&"constructor"===d.value);y&&(i&&this.raise(d.start,"Duplicate constructor in the same class"),l&&this.raise(d.start,"Constructor can't have get/set modifier"),c&&this.raise(d.start,"Constructor can't be a generator"),h&&this.raise(d.start,"Constructor can't be an async function"),o.kind="constructor",i=!0);var m=o["static"]&&("Identifier"===d.type&&"prototype"===d.name||"StringLiteral"===d.type&&"prototype"===d.value);m&&this.raise(d.start,"Classes may not have static property named prototype")}if(u&&(s&&this.raise(o.start,"Duplicate constructor call in the same class"),o.kind="constructorCall",s=!0),"constructor"!==o.kind&&"constructorCall"!==o.kind||!o.decorators||this.raise(o.start,"You can't attach decorators to a class constructor"),this.parseClassMethod(n,o,c,h),l){var v="get"===o.kind?0:1;if(o.params.length!==v){var g=o.start;"get"===o.kind?this.raise(g,"getter should have no params"):this.raise(g,"setter should have exactly one param")}}}r.length&&this.raise(this.state.start,"You have trailing decorators with no method"),t.body=this.finishNode(n,"ClassBody"),this.state.strict=e},c.parseClassProperty=function(t){return this.match(a.types.eq)?(this.hasPlugin("classProperties")||this.unexpected(),this.next(),t.value=this.parseMaybeAssign()):t.value=null,this.eat(a.types.semi)||this.raise(t.value&&t.value.end||t.key.end,"A semicolon is required after a class property"),this.finishNode(t,"ClassProperty")},c.parseClassMethod=function(t,e,s,i){this.parseMethod(e,s,i),t.body.push(this.finishNode(e,"ClassMethod"))},c.parseClassId=function(t,e,s){this.match(a.types.name)?t.id=this.parseIdentifier():s||!e?t.id=null:this.unexpected()},c.parseClassSuper=function(t){t.superClass=this.eat(a.types._extends)?this.parseExprSubscripts():null},c.parseExport=function(t){if(this.next(),this.match(a.types.star)){var e=this.startNode();if(this.next(),!this.hasPlugin("exportExtensions")||!this.eatContextual("as"))return this.parseExportFrom(t,!0),this.finishNode(t,"ExportAllDeclaration");e.exported=this.parseIdentifier(),t.specifiers=[this.finishNode(e,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(t),this.parseExportFrom(t,!0)}else if(this.hasPlugin("exportExtensions")&&this.isExportDefaultSpecifier()){var e=this.startNode();if(e.exported=this.parseIdentifier(!0),t.specifiers=[this.finishNode(e,"ExportDefaultSpecifier")],this.match(a.types.comma)&&this.lookahead().type===a.types.star){this.expect(a.types.comma);var s=this.startNode();this.expect(a.types.star),this.expectContextual("as"),s.exported=this.parseIdentifier(),t.specifiers.push(this.finishNode(s,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(t);this.parseExportFrom(t,!0)}else{if(this.eat(a.types._default)){var i=this.startNode(),r=!1;return this.eat(a.types._function)?i=this.parseFunction(i,!0,!1,!1,!0):this.match(a.types._class)?i=this.parseClass(i,!0,!0):(r=!0,i=this.parseMaybeAssign()),t.declaration=i,r&&this.semicolon(),this.checkExport(t),this.finishNode(t,"ExportDefaultDeclaration")}this.state.type.keyword||this.shouldParseExportDeclaration()?(t.specifiers=[],t.source=null,t.declaration=this.parseExportDeclaration(t)):(t.declaration=null,t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t))}return this.checkExport(t),this.finishNode(t,"ExportNamedDeclaration")},c.parseExportDeclaration=function(){return this.parseStatement(!0)},c.isExportDefaultSpecifier=function(){if(this.match(a.types.name))return"type"!==this.state.value&&"async"!==this.state.value&&"interface"!==this.state.value;if(!this.match(a.types._default))return!1;var t=this.lookahead();return t.type===a.types.comma||t.type===a.types.name&&"from"===t.value},c.parseExportSpecifiersMaybe=function(t){this.eat(a.types.comma)&&(t.specifiers=t.specifiers.concat(this.parseExportSpecifiers()))},c.parseExportFrom=function(t,e){this.eatContextual("from")?(t.source=this.match(a.types.string)?this.parseExprAtom():this.unexpected(),this.checkExport(t)):e?this.unexpected():t.source=null,this.semicolon()},c.shouldParseExportDeclaration=function(){return this.hasPlugin("asyncFunctions")&&this.isContextual("async")},c.checkExport=function(t){if(this.state.decorators.length){var e=t.declaration&&("ClassDeclaration"===t.declaration.type||"ClassExpression"===t.declaration.type);t.declaration&&e||this.raise(t.start,"You can only use decorators on an export when exporting a class"),this.takeDecorators(t.declaration)}},c.parseExportSpecifiers=function(){var t=[],e=!0,s=void 0;for(this.expect(a.types.braceL);!this.eat(a.types.braceR);){if(e)e=!1;else if(this.expect(a.types.comma),this.eat(a.types.braceR))break;var i=this.match(a.types._default);i&&!s&&(s=!0);var r=this.startNode();r.local=this.parseIdentifier(i),r.exported=this.eatContextual("as")?this.parseIdentifier(!0):r.local.__clone(),t.push(this.finishNode(r,"ExportSpecifier"))}return s&&!this.isContextual("from")&&this.unexpected(),t},c.parseImport=function(t){return this.next(),this.match(a.types.string)?(t.specifiers=[],t.source=this.parseExprAtom()):(t.specifiers=[],this.parseImportSpecifiers(t),this.expectContextual("from"),t.source=this.match(a.types.string)?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(t,"ImportDeclaration")},c.parseImportSpecifiers=function(t){var e=!0;if(this.match(a.types.name)){var s=this.state.start,i=this.state.startLoc;if(t.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(),s,i)),!this.eat(a.types.comma))return}if(this.match(a.types.star)){var r=this.startNode();return this.next(),this.expectContextual("as"),r.local=this.parseIdentifier(),this.checkLVal(r.local,!0),void t.specifiers.push(this.finishNode(r,"ImportNamespaceSpecifier"))}for(this.expect(a.types.braceL);!this.eat(a.types.braceR);){if(e)e=!1;else if(this.expect(a.types.comma),this.eat(a.types.braceR))break;var r=this.startNode();r.imported=this.parseIdentifier(!0),r.local=this.eatContextual("as")?this.parseIdentifier():r.imported.__clone(),this.checkLVal(r.local,!0),t.specifiers.push(this.finishNode(r,"ImportSpecifier"))}},c.parseImportSpecifierDefault=function(t,e,s){var i=this.startNodeAt(e,s);return i.local=t,this.checkLVal(i.local,!0),this.finishNode(i,"ImportDefaultSpecifier")}},{"../tokenizer/types":26,"../util/whitespace":29,"./index":5,"babel-runtime/core-js/get-iterator":30,"babel-runtime/core-js/object/create":31,"babel-runtime/helpers/interop-require-default":35}],10:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../tokenizer/types"),n=t("./index"),a=i(n),o=t("../util/whitespace"),u=a["default"].prototype;u.addExtra=function(t,e,s){if(t){var i=t.extra=t.extra||{};i[e]=s}},u.isRelational=function(t){return this.match(r.types.relational)&&this.state.value===t},u.expectRelational=function(t){this.isRelational(t)?this.next():this.unexpected()},u.isContextual=function(t){return this.match(r.types.name)&&this.state.value===t},u.eatContextual=function(t){return this.state.value===t&&this.eat(r.types.name)},u.expectContextual=function(t){this.eatContextual(t)||this.unexpected()},u.canInsertSemicolon=function(){return this.match(r.types.eof)||this.match(r.types.braceR)||o.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.start))},u.isLineTerminator=function(){return this.eat(r.types.semi)||this.canInsertSemicolon()},u.semicolon=function(){this.isLineTerminator()||this.unexpected()},u.expect=function(t){return this.eat(t)||this.unexpected()},u.unexpected=function(t){this.raise(null!=t?t:this.state.start,"Unexpected token")}},{"../tokenizer/types":26,"../util/whitespace":29,"./index":5,"babel-runtime/helpers/interop-require-default":35}],11:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../../tokenizer/context"),n=t("../../parser"),a=i(n);r.types.cssx=new r.TokContext("cssx"),r.types.cssxDefinition=new r.TokContext("cssxDefinition"),r.types.cssxSelector=new r.TokContext("cssxSelector"),r.types.cssxRules=new r.TokContext("cssxRules"),r.types.cssxProperty=new r.TokContext("cssxProperty"),r.types.cssxValue=new r.TokContext("cssxValue"),r.types.cssxMediaQuery=new r.TokContext("CSSXMediaQuery");var o=a["default"].prototype,u=function(t,e){o["cssx"+t+"In"]=function(){var t=this.curContext();t!==e&&this.state.context.push(e)},o["cssx"+t+"Out"]=function(){var t=this.curContext();t!==e&&this.raise(this.state.start,"CSSX: Not in "+e.token+" context"),this.state.context.length-=1}};u("",r.types.cssx),u("MediaQuery",r.types.cssxMediaQuery),u("Definition",r.types.cssxDefinition)},{"../../parser":5,"../../tokenizer/context":23,"babel-runtime/helpers/interop-require-default":35}],12:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../../parser"),n=i(r),a=n["default"].prototype;a.cssxExpressionRegister=function(t){t&&t.length>0&&(this.state._cssxExpressions=t)},a.cssxExpressionSet=function(t){var e=this,s=void 0,i=void 0;this.state._cssxExpressions&&this.state._cssxExpressions.length>0&&(t.expressions=this.state._cssxExpressions.map(function(t){return s=t.end-t.start,i=e.state.input.substr(t.start,s).substr(1,s-2),""===i?!1:{start:t.start,end:t.end,contextLoc:{start:t.inner.start,end:t.inner.end}}}).filter(function(t){return t!==!1})),this.state._cssxExpressions=!1}},{"../../parser":5,"babel-runtime/helpers/interop-require-default":35}],13:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../../parser"),n=i(r),a=t("../../tokenizer"),o=t("./utilities"),u=n["default"].prototype,p="@media ";u.cssxIsMediaQuery=function(){return 0===this.state.value.toString().indexOf(p)?!0:!1},u.cssxGetPreviousToken=function(){var t=arguments.length<=0||void 0===arguments[0]?0:arguments[0];return this.state.tokens[this.state.tokens.length-(t+1)]},u.cssxMatchPreviousToken=function(t,e){var s=this.cssxGetPreviousToken(e);return s&&s.type===t?!0:!1},u.cssxMatchNextToken=function(){var t=void 0,e=void 0,s=void 0,i=void 0;return 1===arguments.length?(t=this.lookahead(),t&&t.type===arguments[0]?!0:!1):2===arguments.length?(i=this.state,this.state=i.clone(!0),this.isLookahead=!0,this.next(),e=this.state.clone(!0),this.next(),s=this.state.clone(!0),this.isLookahead=!1,this.state=i,e&&e.type===arguments[0]&&s&&s.type===arguments[1]?!0:!1):void 0},u.cssxLookahead=function(){var t=arguments.length<=0||void 0===arguments[0]?2:arguments[0],e=this.state,s=[];for(this.state=e.clone(!0),this.isLookahead=!0;t>0;)this.next(),s.push(this.state.clone(!0)),--t;return this.isLookahead=!1,this.state=e,{stack:s,last:s[s.length-1],first:s[0]}},u.cssxClonePosition=function(t){return{line:t.line,column:t.column}},u.cssxDebugComments=function(t){return t&&0!==t.length?JSON.stringify(t.map(function(t){return{type:t.type,value:t.value}})):null},u.cssxClearSpaceAtTheEnd=function(t){return" "===t.charAt(t.length-1)?(--this.state.pos,t.substr(0,t.length-1)):t},u.cssxFinishTokenAt=function(t,e,s,i){this.state.end=s,this.state.endLoc=i;var r=this.state.type;this.state.type=t,this.state.value=e,this.updateContext(r)},u.replaceCurrentTokenType=function(t){this.state.type=t},u.cssxStoreNextCharAsToken=function(t){var e=this.curContext();++this.state.pos,this.finishToken(t),this.state.tokens.push(new a.Token(this.state)),e&&e.preserveSpace||this.skipSpace(),this.cssxSyncLocPropsToCurPos()},u.cssxStoreCurrentToken=function(){this.state.tokens.push(new a.Token(this.state)),this.cssxSyncLocPropsToCurPos()},u.cssxSyncLocPropsToCurPos=function(t){var e="undefined"==typeof t?this.state.pos:t;this.state.start=this.state.end=e,this.state.startLoc=this.state.endLoc=o.posToLoc(e,this.state.input)},u.cssxSyncEndTokenStateToCurPos=function(t){var e=("undefined"==typeof t?this.state.pos:t,o.posToLoc(this.state.pos,this.state.input,!0));this.state.endLoc.line=e.line,this.state.endLoc.column=e.column,this.state.lineStart=e.lineStart,this.state.curLine=e.curLine}},{"../../parser":5,"../../tokenizer":24,"./utilities":19,"babel-runtime/helpers/interop-require-default":35}],14:[function(t,e,s){"use strict";function i(t){t.extend("parseStatement",function(t){return function(e,s){return this.cssxMatchPreviousToken(n.types.cssxStart)&&this.curContext()!==a.types.cssxDefinition?(this.cssxDefinitionIn(),this.cssxParse()):this.match(n.types.cssxSelector)?this.cssxIsMediaQuery()?this.cssxParseMediaQueryElement():this.cssxParseElement():t.call(this,e,s)}}),t.extend("parseBlock",function(t){return function(e){var s,i,r=this,o=function(){return t.call(r,e)},u=this.curContext(),p=[];if(u===a.types.cssxRules&&this.match(n.types.cssxRulesStart)){if(s=this.startNode(),this.match(n.types.cssxRulesStart)&&this.lookahead().type===n.types.braceR)this.next();else{for(;!this.match(n.types.cssxRulesEnd)&&!this.match(n.types.eof);)p.push(this.cssxParseRule(this.cssxReadProperty(),this.cssxReadValue()));this.state.pos>=this.input.length&&this.finishToken(n.types.eof)}return s.body=p,i=this.cssxGetPreviousToken(),this.finishNodeAt(s,"CSSXRules",i.end,i.loc.end)}return o()}}),t.extend("readToken",function(t){return function(e){var s=this,i=function(){return t.call(s,e)},r=this.curContext();if(this.isLookahead)return i();if(this.match(n.types.cssxSelector)&&this.cssxMatchNextToken(n.types.braceL))return++this.state.pos,this.finishToken(n.types.cssxRulesStart);if(this.match(n.types.cssxSelector)&&this.cssxMatchNextToken(n.types.parenR))return void this.finishToken(n.types.cssxRulesEnd);if(this.match(n.types.cssxRulesStart))return this.cssxMatchNextToken(n.types.braceR)?this.cssxStoreNextCharAsToken(n.types.cssxRulesEnd):this.finishToken(n.types.cssxRulesStart);if(this.match(n.types.cssxProperty)&&58===e)return this.cssxStoreNextCharAsToken(n.types.colon);if(this.match(n.types.cssxValue)&&59===e)return this.cssxStoreNextCharAsToken(n.types.semi),void(this.cssxMatchNextToken(n.types.braceR)&&this.cssxStoreNextCharAsToken(n.types.cssxRulesEnd));if(this.match(n.types.cssxValue)&&this.cssxMatchNextToken(n.types.braceR))return this.cssxStoreNextCharAsToken(n.types.cssxRulesEnd);if(!this.match(n.types.cssxRulesEnd)||r!==a.types.cssxMediaQuery){if(this.match(n.types.cssxRulesEnd)&&this.cssxMatchNextToken(n.types.parenR)||this.match(n.types.cssxMediaQueryEnd)&&this.cssxMatchNextToken(n.types.parenR))return++this.state.pos,void this.finishToken(n.types.cssxEnd);if(!this.cssxEntryPoint())return r===a.types.cssxDefinition||r===a.types.cssxMediaQuery?(this.skipSpace(),this.cssxReadSelector()):i()}}}),t.extend("getTokenFromCode",function(t){return function(e){var s=this,i=function(){return t.call(s,e)};return 35===e&&(this.match(n.types.cssxStart)||this.match(n.types.cssxRulesEnd))?(++this.state.pos,this.finishToken(n.types.string,"#")):i()}}),t.extend("parseExprAtom",function(t){return function(e){return this.match(n.types.cssxStart)?(this.cssxDefinitionIn(),this.cssxParse()):t.call(this,e)}}),t.extend("processComment",function(t){return function(e){return"CSSXRule"===e.type&&(this.state.trailingComments.length=0,this.state.leadingComments.length=0),t.call(this,e)}})}var r=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0,s["default"]=i;var n=t("../../tokenizer/types"),a=t("../../tokenizer/context"),o=t("../../parser"),u=r(o);t("../../util/location"),t("./utilities");t("./types"),t("./context"),t("./parsers"),t("./readers"),t("./helpers"),t("./expressions");var p=u["default"].prototype;p.cssxEntryPoint=function(t){var e=this.lookahead(),s=void 0,i=void 0,r=void 0,a=void 0;return e.type===n.types.name&&"cssx"===e.value&&this.cssxMatchNextToken(n.types.name,n.types.parenL)?(a=this.state.clone(),r=this.cssxLookahead(2),s=r.first,i=r.last,this.cssxIn(),this.state.pos=i.end,this.finishToken(n.types.cssxStart),this.cssxSyncEndTokenStateToCurPos(),this.cssxMatchNextToken(n.types.parenR)?(this.state=a,!1):(this.cssxStoreCurrentToken(),!0)):!1},p.cssxRulesEntryPoint=function(t){return this.match(n.types.braceL)&&this.cssxMatchNextToken(n.types.name,n.types.colon)},e.exports=s["default"]},{"../../parser":5,"../../tokenizer/context":23,"../../tokenizer/types":26,"../../util/location":28,"./context":11,"./expressions":12,"./helpers":13,"./parsers":15,"./readers":16,"./types":18,"./utilities":19,"babel-runtime/helpers/interop-require-default":35}],15:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../../parser"),n=i(r),a=t("../../tokenizer/types"),o=n["default"].prototype;o.cssxParse=function(){var t=this.cssxGetPreviousToken(),e=this.startNodeAt(t.start,t.loc.start);return this.skipSpace(),this.cssxReadSelector(),this.parseBlockBody(e,!0,!1,a.types.cssxEnd),this.finishNode(e,"CSSXDefinition"),e},o.cssxParseExpression=function(){var t=void 0,e=void 0,s=void 0;for(e=this.cssxGetPreviousToken(),t=this.startNodeAt(e.start,e.loc.start),t.body=[];this.match(a.types.cssxSelector);)this.cssxIsMediaQuery()?t.body.push(this.cssxParseMediaQueryElement()):t.body.push(this.cssxParseElement());return s=this.finishNodeAt(t,"CSSXExpression",this.state.end,this.state.endLoc),this.next(),s},o.cssxParseElement=function(){var t=void 0,e=void 0,s=void 0,i=void 0;return t=this.startNodeAt(this.state.start,this.state.startLoc),e=this.startNodeAt(this.state.start,this.state.startLoc),e.value=this.state.value,this.cssxExpressionSet(e),t.selector=this.finishNodeAt(e,"CSSXSelector",this.state.end,this.state.endLoc),this.next(),this.match(a.types.cssxRulesEnd)||(t.body=this.parseBlock()),i=this.cssxGetPreviousToken(),s=this.finishNodeAt(t,"CSSXElement",i.end,i.loc.end),this.nextToken(),s},o.cssxParseMediaQueryElement=function(){var t=void 0,e=void 0;if(t=this.startNodeAt(this.state.start,this.state.startLoc),t.query=this.state.value,this.cssxExpressionSet(t),this.cssxMediaQueryIn(),this.cssxFinishTokenAt(a.types.cssxMediaQuery,this.state.value,this.state.end,this.state.endLoc),this.cssxStoreCurrentToken(),this.cssxMatchNextToken(a.types.braceL)||this.raise(this.state.pos,"CSSX: expected { after query definition"),++this.state.pos,this.finishToken(a.types.cssxMediaQueryStart),this.cssxMatchNextToken(a.types.braceR))this.cssxStoreCurrentToken(),this.skipSpace(),this.cssxSyncLocPropsToCurPos();else if(this.next(),t.body=[],this.match(a.types.cssxSelector))for(t.body.push(this.cssxParseElement());!this.cssxMatchNextToken(a.types.braceR);)this.match(a.types.cssxRulesEnd)&&this.cssxReadSelector(),this.cssxMatchNextToken(a.types.parenR)&&this.raise(this.state.pos,"CSSX: unclosed media query block"),t.body.push(this.cssxParseElement());else this.raise(this.state.pos,"CSSX: expected css selector after media query definition");return++this.state.pos,this.finishToken(a.types.cssxMediaQueryEnd),e=this.finishNodeAt(t,"CSSXMediaQueryElement",this.state.end,this.state.endLoc),this.next(),e},o.cssxParseRule=function(t,e){var s=this.startNodeAt(t.start,t.loc.start),i=e.end,r=this.cssxClonePosition(e.loc.end);return(this.match(a.types.semi)||this.match(a.types.cssxRulesEnd)&&this.cssxMatchPreviousToken(a.types.semi,1))&&(++r.column,++i),s.label=t,s.body=e,this.finishNodeAt(s,"CSSXRule",i,r)},o.cssxParseRuleChild=function(t,e,s,i){var r=this.startNodeAt(s,i);return this.cssxExpressionSet(r),r.name=e,this.finishNodeAt(r,t,this.state.lastTokEnd,this.state.lastTokEndLoc)}},{"../../parser":5,"../../tokenizer/types":26,"babel-runtime/helpers/interop-require-default":35}],16:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../../parser"),n=i(r),a=t("../../util/identifier"),o=t("../../tokenizer/types"),u=t("../../tokenizer/context"),p=t("./settings"),c=t("./utilities"),l=n["default"].prototype;l.cssxReadWord=function(t){var e=this,s="",i=!0,r=void 0,n=void 0,o=!1,u=!1,p=["url(data:",41],c=[96,96],l=[40,41],h=!1,f=[],d=0;for(r=this.state.pos,n=function(){return e.input.slice(r,e.state.pos)},this.state.containsEsc=!1;this.state.pos<this.input.length;){var y=this.fullCharCodeAtPos();if(n()===p[0]&&(o=!0),y===p[1]&&(o=!1),y===l[0]&&(u=!0),t.call(this,y)||o||u||y===c[0]||h!==!1){var m=65535>=y?1:2;this.state.pos+=m,y===c[1]&&h?(h.end=this.state.pos,h.inner.end=d+1,f.push(h),h=!1):y!==c[0]||h||(h={start:this.state.pos-1,inner:{start:d}}),10===y&&(++this.state.curLine,this.state.lineStart=this.state.pos)}else{if(92!==y)break;this.state.containsEsc=!0,s+=this.input.slice(r,this.state.pos);var v=this.state.pos;117!==this.input.charCodeAt(++this.state.pos)&&this.raise(this.state.pos,"CSSX: expecting Unicode escape sequence \\uXXXX"), ++this.state.pos;var g=this.readCodePoint();(i?a.isIdentifierStart:a.isIdentifierChar)(g,!0)||this.raise(v,"CSSX: invalid Unicode escape"),s+=codePointToString(g),r=this.state.pos}y===l[1]&&(u=!1),i=!1,++d}return s+=n(),{str:s,expressions:f}},l.cssxReadSelector=function(t){var e=void 0,s=void 0,i=void 0,r=void 0;this.state.context.push(u.types.cssxSelector),e=this.state.curPosition(),s=this.state.pos,r=this.cssxReadWord(l.cssxReadSelectorCharUntil),i=this.cssxClearSpaceAtTheEnd(r.str),this.cssxExpressionRegister(r.expressions),this.state.startLoc=e,this.state.start=s,this.finishToken(o.types.cssxSelector,i),this.skipSpace()},l.cssxReadProperty=function(){var t=void 0,e=void 0,s=void 0,i=void 0,r=void 0;return this.match(o.types.cssxRulesStart)&&this.next(),t=this.state.curPosition(),e=this.state.pos,r=this.cssxReadWord(l.cssxReadPropCharUntil),s=r.str,""===s&&this.raise(this.state.pos,"CSSX: no CSS property provided"),this.cssxExpressionRegister(r.expressions),this.state.startLoc=t,this.state.start=e,this.finishToken(o.types.cssxProperty,s),this.lookahead().type!==o.types.colon&&this.raise(this.state.pos,"CSSX: expecting a colon after CSS property"),this.next(),i=this.cssxParseRuleChild("CSSXProperty",s,e,t)},l.cssxReadValue=function(){var t=void 0,e=void 0,s=void 0,i=void 0,r=void 0;return t=this.state.curPosition(),e=this.state.pos,r=this.cssxReadWord(l.cssxReadValueCharUntil),s=this.cssxClearSpaceAtTheEnd(r.str),this.cssxExpressionRegister(r.expressions),this.state.start=e,this.state.startLoc=t,this.finishToken(o.types.cssxValue,s),this.next(),i=this.cssxParseRuleChild("CSSXValue",s,e,t)},l.cssxReadSelectorCharUntil=function(t){return p.CSSXSelectorAllowedCodes.indexOf(t)>=0||c.isNumber(t)?!0:123===t?!1:a.isIdentifierChar(t)},l.cssxReadValueCharUntil=function(t){return p.CSSXValueAllowedCodes.indexOf(t)>=0?!0:a.isIdentifierChar(t)},l.cssxReadPropCharUntil=function(t){return p.CSSXPropertyAllowedCodes.indexOf(t)>=0?!0:a.isIdentifierChar(t)}},{"../../parser":5,"../../tokenizer/context":23,"../../tokenizer/types":26,"../../util/identifier":27,"./settings":17,"./utilities":19,"babel-runtime/helpers/interop-require-default":35}],17:[function(t,e,s){"use strict";s.__esModule=!0;var i=(t("../../tokenizer/types"),t("./utilities")),r=["-"].map(i.stringToCode),n=[" ","\n"," ","#",".","-","(",")","[","]","'",'"',"%",",",":","/","\\"].map(i.stringToCode),a=[" ","*",">","+","~",".",":","=","[","]",'"',"-","!","?","@","#","$","%","^","&","'","|",",","\n"].map(i.stringToCode);s["default"]={CSSXPropertyAllowedCodes:r,CSSXValueAllowedCodes:n,CSSXSelectorAllowedCodes:a},e.exports=s["default"]},{"../../tokenizer/types":26,"./utilities":19}],18:[function(t,e,s){"use strict";var i=t("../../tokenizer/types"),r=t("../../tokenizer/context");i.types.cssxStart=new i.TokenType("CSSXStart"),i.types.cssxEnd=new i.TokenType("CSSXEnd"),i.types.cssxSelector=new i.TokenType("CSSXSelector"),i.types.cssxRulesStart=new i.TokenType("CSSXRulesStart"),i.types.cssxRulesEnd=new i.TokenType("CSSXRulesEnd"),i.types.cssxProperty=new i.TokenType("CSSXProperty"),i.types.cssxValue=new i.TokenType("CSSXValue"),i.types.cssxMediaQuery=new i.TokenType("CSSXMediaQuery"),i.types.cssxMediaQueryStart=new i.TokenType("CSSXMediaQueryStart"),i.types.cssxMediaQueryEnd=new i.TokenType("CSSXMediaQueryEnd"),i.types.cssxRulesStart.updateContext=function(t){t===i.types.cssxSelector&&this.state.context.push(r.types.cssxRules)},i.types.cssxRulesEnd.updateContext=function(t){(t===i.types.cssxValue||t===i.types.cssxRulesStart||t===i.types.semi)&&(this.state.context.length-=1)},i.types.cssxEnd.updateContext=function(t){this.cssxDefinitionOut(),this.cssxOut()},i.types.cssxSelector.updateContext=function(t){this.state.context.length-=1},i.types.cssxMediaQueryEnd.updateContext=function(t){this.cssxMediaQueryOut()}},{"../../tokenizer/context":23,"../../tokenizer/types":26}],19:[function(t,e,s){"use strict";function i(t){return String(t).charCodeAt(0)}function r(t,e,s){for(var i=1,r=0,n=0,a=0;r<e.length&&r!==t;)"\n"===e.charAt(r)?(n=0,a=r+1,++i):++n,++r;return s?{line:i,curLine:i,column:n,lineStart:a}:{line:i,column:n}}function n(t){return t>47&&58>t}s.__esModule=!0,s.stringToCode=i,s.posToLoc=r,s.isNumber=n},{}],20:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var r=t("../tokenizer/types"),n=t("../parser"),a=i(n),o=a["default"].prototype;o.flowParseTypeInitialiser=function(t){var e=this.state.inType;this.state.inType=!0,this.expect(t||r.types.colon);var s=this.flowParseType();return this.state.inType=e,s},o.flowParseDeclareClass=function(t){return this.next(),this.flowParseInterfaceish(t,!0),this.finishNode(t,"DeclareClass")},o.flowParseDeclareFunction=function(t){this.next();var e=t.id=this.parseIdentifier(),s=this.startNode(),i=this.startNode();this.isRelational("<")?s.typeParameters=this.flowParseTypeParameterDeclaration():s.typeParameters=null,this.expect(r.types.parenL);var n=this.flowParseFunctionTypeParams();return s.params=n.params,s.rest=n.rest,this.expect(r.types.parenR),s.returnType=this.flowParseTypeInitialiser(),i.typeAnnotation=this.finishNode(s,"FunctionTypeAnnotation"),e.typeAnnotation=this.finishNode(i,"TypeAnnotation"),this.finishNode(e,e.type),this.semicolon(),this.finishNode(t,"DeclareFunction")},o.flowParseDeclare=function(t){return this.match(r.types._class)?this.flowParseDeclareClass(t):this.match(r.types._function)?this.flowParseDeclareFunction(t):this.match(r.types._var)?this.flowParseDeclareVariable(t):this.isContextual("module")?this.flowParseDeclareModule(t):this.isContextual("type")?this.flowParseDeclareTypeAlias(t):this.isContextual("interface")?this.flowParseDeclareInterface(t):void this.unexpected()},o.flowParseDeclareVariable=function(t){return this.next(),t.id=this.flowParseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(t,"DeclareVariable")},o.flowParseDeclareModule=function(t){this.next(),this.match(r.types.string)?t.id=this.parseExprAtom():t.id=this.parseIdentifier();var e=t.body=this.startNode(),s=e.body=[];for(this.expect(r.types.braceL);!this.match(r.types.braceR);){var i=this.startNode();this.next(),s.push(this.flowParseDeclare(i))}return this.expect(r.types.braceR),this.finishNode(e,"BlockStatement"),this.finishNode(t,"DeclareModule")},o.flowParseDeclareTypeAlias=function(t){return this.next(),this.flowParseTypeAlias(t),this.finishNode(t,"DeclareTypeAlias")},o.flowParseDeclareInterface=function(t){return this.next(),this.flowParseInterfaceish(t),this.finishNode(t,"DeclareInterface")},o.flowParseInterfaceish=function(t,e){if(t.id=this.parseIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t["extends"]=[],t.mixins=[],this.eat(r.types._extends))do t["extends"].push(this.flowParseInterfaceExtends());while(this.eat(r.types.comma));if(this.isContextual("mixins")){this.next();do t.mixins.push(this.flowParseInterfaceExtends());while(this.eat(r.types.comma))}t.body=this.flowParseObjectType(e)},o.flowParseInterfaceExtends=function(){var t=this.startNode();return t.id=this.parseIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterInstantiation():t.typeParameters=null,this.finishNode(t,"InterfaceExtends")},o.flowParseInterface=function(t){return this.flowParseInterfaceish(t,!1),this.finishNode(t,"InterfaceDeclaration")},o.flowParseTypeAlias=function(t){return t.id=this.parseIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.right=this.flowParseTypeInitialiser(r.types.eq),this.semicolon(),this.finishNode(t,"TypeAlias")},o.flowParseTypeParameterDeclaration=function(){var t=this.startNode();for(t.params=[],this.expectRelational("<");!this.isRelational(">");)t.params.push(this.flowParseExistentialTypeParam()||this.flowParseTypeAnnotatableIdentifier()),this.isRelational(">")||this.expect(r.types.comma);return this.expectRelational(">"),this.finishNode(t,"TypeParameterDeclaration")},o.flowParseExistentialTypeParam=function(){if(this.match(r.types.star)){var t=this.startNode();return this.next(),this.finishNode(t,"ExistentialTypeParam")}},o.flowParseTypeParameterInstantiation=function(){var t=this.startNode(),e=this.state.inType;for(t.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)t.params.push(this.flowParseExistentialTypeParam()||this.flowParseType()),this.isRelational(">")||this.expect(r.types.comma);return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterInstantiation")},o.flowParseObjectPropertyKey=function(){return this.match(r.types.num)||this.match(r.types.string)?this.parseExprAtom():this.parseIdentifier(!0)},o.flowParseObjectTypeIndexer=function(t,e){return t["static"]=e,this.expect(r.types.bracketL),t.id=this.flowParseObjectPropertyKey(),t.key=this.flowParseTypeInitialiser(),this.expect(r.types.bracketR),t.value=this.flowParseTypeInitialiser(),this.flowObjectTypeSemicolon(),this.finishNode(t,"ObjectTypeIndexer")},o.flowParseObjectTypeMethodish=function(t){for(t.params=[],t.rest=null,t.typeParameters=null,this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(r.types.parenL);this.match(r.types.name);)t.params.push(this.flowParseFunctionTypeParam()),this.match(r.types.parenR)||this.expect(r.types.comma);return this.eat(r.types.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),this.expect(r.types.parenR),t.returnType=this.flowParseTypeInitialiser(),this.finishNode(t,"FunctionTypeAnnotation")},o.flowParseObjectTypeMethod=function(t,e,s,i){var r=this.startNodeAt(t,e);return r.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t,e)),r["static"]=s,r.key=i,r.optional=!1,this.flowObjectTypeSemicolon(),this.finishNode(r,"ObjectTypeProperty")},o.flowParseObjectTypeCallProperty=function(t,e){var s=this.startNode();return t["static"]=e,t.value=this.flowParseObjectTypeMethodish(s),this.flowObjectTypeSemicolon(),this.finishNode(t,"ObjectTypeCallProperty")},o.flowParseObjectType=function(t){var e=this.startNode(),s=void 0,i=void 0,n=void 0;for(e.callProperties=[],e.properties=[],e.indexers=[],this.expect(r.types.braceL);!this.match(r.types.braceR);){var a=!1,o=this.state.start,u=this.state.startLoc;s=this.startNode(),t&&this.isContextual("static")&&(this.next(),n=!0),this.match(r.types.bracketL)?e.indexers.push(this.flowParseObjectTypeIndexer(s,n)):this.match(r.types.parenL)||this.isRelational("<")?e.callProperties.push(this.flowParseObjectTypeCallProperty(s,t)):(i=n&&this.match(r.types.colon)?this.parseIdentifier():this.flowParseObjectPropertyKey(),this.isRelational("<")||this.match(r.types.parenL)?e.properties.push(this.flowParseObjectTypeMethod(o,u,n,i)):(this.eat(r.types.question)&&(a=!0),s.key=i,s.value=this.flowParseTypeInitialiser(),s.optional=a,s["static"]=n,this.flowObjectTypeSemicolon(),e.properties.push(this.finishNode(s,"ObjectTypeProperty"))))}return this.expect(r.types.braceR),this.finishNode(e,"ObjectTypeAnnotation")},o.flowObjectTypeSemicolon=function(){this.eat(r.types.semi)||this.eat(r.types.comma)||this.match(r.types.braceR)||this.unexpected()},o.flowParseGenericType=function(t,e,s){var i=this.startNodeAt(t,e);for(i.typeParameters=null,i.id=s;this.eat(r.types.dot);){var n=this.startNodeAt(t,e);n.qualification=i.id,n.id=this.parseIdentifier(),i.id=this.finishNode(n,"QualifiedTypeIdentifier")}return this.isRelational("<")&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")},o.flowParseTypeofType=function(){var t=this.startNode();return this.expect(r.types._typeof),t.argument=this.flowParsePrimaryType(),this.finishNode(t,"TypeofTypeAnnotation")},o.flowParseTupleType=function(){var t=this.startNode();for(t.types=[],this.expect(r.types.bracketL);this.state.pos<this.input.length&&!this.match(r.types.bracketR)&&(t.types.push(this.flowParseType()),!this.match(r.types.bracketR));)this.expect(r.types.comma);return this.expect(r.types.bracketR),this.finishNode(t,"TupleTypeAnnotation")},o.flowParseFunctionTypeParam=function(){var t=!1,e=this.startNode();return e.name=this.parseIdentifier(),this.eat(r.types.question)&&(t=!0),e.optional=t,e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeParam")},o.flowParseFunctionTypeParams=function(){for(var t={params:[],rest:null};this.match(r.types.name);)t.params.push(this.flowParseFunctionTypeParam()),this.match(r.types.parenR)||this.expect(r.types.comma);return this.eat(r.types.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),t},o.flowIdentToTypeAnnotation=function(t,e,s,i){switch(i.name){case"any":return this.finishNode(s,"AnyTypeAnnotation");case"void":return this.finishNode(s,"VoidTypeAnnotation");case"bool":case"boolean":return this.finishNode(s,"BooleanTypeAnnotation");case"mixed":return this.finishNode(s,"MixedTypeAnnotation");case"number":return this.finishNode(s,"NumberTypeAnnotation");case"string":return this.finishNode(s,"StringTypeAnnotation");default:return this.flowParseGenericType(t,e,i)}},o.flowParsePrimaryType=function(){var t=this.state.start,e=this.state.startLoc,s=this.startNode(),i=void 0,n=void 0,a=!1;switch(this.state.type){case r.types.name:return this.flowIdentToTypeAnnotation(t,e,s,this.parseIdentifier());case r.types.braceL:return this.flowParseObjectType();case r.types.bracketL:return this.flowParseTupleType();case r.types.relational:if("<"===this.state.value)return s.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(r.types.parenL),i=this.flowParseFunctionTypeParams(),s.params=i.params,s.rest=i.rest,this.expect(r.types.parenR),this.expect(r.types.arrow),s.returnType=this.flowParseType(),this.finishNode(s,"FunctionTypeAnnotation");case r.types.parenL:if(this.next(),!this.match(r.types.parenR)&&!this.match(r.types.ellipsis))if(this.match(r.types.name)){var o=this.lookahead().type;a=o!==r.types.question&&o!==r.types.colon}else a=!0;return a?(n=this.flowParseType(),this.expect(r.types.parenR),this.eat(r.types.arrow)&&this.raise(s,"Unexpected token =>. It looks like you are trying to write a function type, but you ended up writing a grouped type followed by an =>, which is a syntax error. Remember, function type parameters are named so function types look like (name1: type1, name2: type2) => returnType. You probably wrote (type1) => returnType"),n):(i=this.flowParseFunctionTypeParams(),s.params=i.params,s.rest=i.rest,this.expect(r.types.parenR),this.expect(r.types.arrow),s.returnType=this.flowParseType(),s.typeParameters=null,this.finishNode(s,"FunctionTypeAnnotation"));case r.types.string:return s.value=this.state.value,this.addExtra(s,"rawValue",s.value),this.addExtra(s,"raw",this.input.slice(this.state.start,this.state.end)),this.next(),this.finishNode(s,"StringLiteralTypeAnnotation");case r.types._true:case r.types._false:return s.value=this.match(r.types._true),this.next(),this.finishNode(s,"BooleanLiteralTypeAnnotation");case r.types.num:return s.value=this.state.value,this.addExtra(s,"rawValue",s.value),this.addExtra(s,"raw",this.input.slice(this.state.start,this.state.end)),this.next(),this.finishNode(s,"NumericLiteralTypeAnnotation");case r.types._null:return s.value=this.match(r.types._null),this.next(),this.finishNode(s,"NullLiteralTypeAnnotation");case r.types._this:return s.value=this.match(r.types._this),this.next(),this.finishNode(s,"ThisTypeAnnotation");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType()}this.unexpected()},o.flowParsePostfixType=function(){var t=this.startNode(),e=t.elementType=this.flowParsePrimaryType();return this.match(r.types.bracketL)?(this.expect(r.types.bracketL),this.expect(r.types.bracketR),this.finishNode(t,"ArrayTypeAnnotation")):e},o.flowParsePrefixType=function(){var t=this.startNode();return this.eat(r.types.question)?(t.typeAnnotation=this.flowParsePrefixType(),this.finishNode(t,"NullableTypeAnnotation")):this.flowParsePostfixType()},o.flowParseIntersectionType=function(){var t=this.startNode(),e=this.flowParsePrefixType();for(t.types=[e];this.eat(r.types.bitwiseAND);)t.types.push(this.flowParsePrefixType());return 1===t.types.length?e:this.finishNode(t,"IntersectionTypeAnnotation")},o.flowParseUnionType=function(){var t=this.startNode(),e=this.flowParseIntersectionType();for(t.types=[e];this.eat(r.types.bitwiseOR);)t.types.push(this.flowParseIntersectionType());return 1===t.types.length?e:this.finishNode(t,"UnionTypeAnnotation")},o.flowParseType=function(){var t=this.state.inType;this.state.inType=!0;var e=this.flowParseUnionType();return this.state.inType=t,e},o.flowParseTypeAnnotation=function(){var t=this.startNode();return t.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(t,"TypeAnnotation")},o.flowParseTypeAnnotatableIdentifier=function(t,e){var s=this.parseIdentifier(),i=!1;return e&&this.eat(r.types.question)&&(this.expect(r.types.question),i=!0),(t||this.match(r.types.colon))&&(s.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(s,s.type)),i&&(s.optional=!0,this.finishNode(s,s.type)),s},s["default"]=function(t){function e(t){return t.expression.typeAnnotation=t.typeAnnotation,t.expression}t.extend("parseFunctionBody",function(t){return function(e,s){return this.match(r.types.colon)&&!s&&(e.returnType=this.flowParseTypeAnnotation()),t.call(this,e,s)}}),t.extend("parseStatement",function(t){return function(e,s){if(this.state.strict&&this.match(r.types.name)&&"interface"===this.state.value){var i=this.startNode();return this.next(),this.flowParseInterface(i)}return t.call(this,e,s)}}),t.extend("parseExpressionStatement",function(t){return function(e,s){if("Identifier"===s.type)if("declare"===s.name){if(this.match(r.types._class)||this.match(r.types.name)||this.match(r.types._function)||this.match(r.types._var))return this.flowParseDeclare(e)}else if(this.match(r.types.name)){if("interface"===s.name)return this.flowParseInterface(e);if("type"===s.name)return this.flowParseTypeAlias(e)}return t.call(this,e,s)}}),t.extend("shouldParseExportDeclaration",function(t){return function(){return this.isContextual("type")||this.isContextual("interface")||t.call(this)}}),t.extend("parseParenItem",function(){return function(t,e,s,i){var n=this.state.potentialArrowAt=s;if(this.match(r.types.colon)){var a=this.startNodeAt(e,s);if(a.expression=t,a.typeAnnotation=this.flowParseTypeAnnotation(),i&&!this.match(r.types.arrow)&&this.unexpected(),n&&this.eat(r.types.arrow)){var o="SequenceExpression"===t.type?t.expressions:[t],u=this.parseArrowExpression(this.startNodeAt(e,s),o);return u.returnType=a.typeAnnotation,u}return this.finishNode(a,"TypeCastExpression")}return t}}),t.extend("parseExport",function(t){return function(e){return e=t.call(this,e),"ExportNamedDeclaration"===e.type&&(e.exportKind=e.exportKind||"value"),e}}),t.extend("parseExportDeclaration",function(t){return function(e){if(this.isContextual("type")){e.exportKind="type";var s=this.startNode();return this.next(),this.match(r.types.braceL)?(e.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(e),null):this.flowParseTypeAlias(s)}if(this.isContextual("interface")){e.exportKind="type";var s=this.startNode();return this.next(),this.flowParseInterface(s)}return t.call(this,e)}}),t.extend("parseClassId",function(t){return function(e){t.apply(this,arguments),this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}}),t.extend("isKeyword",function(t){return function(e){return this.state.inType&&"void"===e?!1:t.call(this,e)}}),t.extend("readToken",function(t){return function(e){return!this.state.inType||62!==e&&60!==e?t.call(this,e):this.finishOp(r.types.relational,1)}}),t.extend("jsx_readToken",function(t){return function(){return this.state.inType?void 0:t.call(this)}}),t.extend("toAssignable",function(t){return function(s){return"TypeCastExpression"===s.type?e(s):t.apply(this,arguments)}}),t.extend("toAssignableList",function(t){return function(s,i){for(var r=0;r<s.length;r++){var n=s[r];n&&"TypeCastExpression"===n.type&&(s[r]=e(n))}return t.call(this,s,i)}}),t.extend("toReferencedList",function(){return function(t){for(var e=0;e<t.length;e++){var s=t[e];s&&s._exprListItem&&"TypeCastExpression"===s.type&&this.raise(s.start,"Unexpected type cast")}return t}}),t.extend("parseExprListItem",function(t){return function(e,s){var i=this.startNode(),n=t.call(this,e,s);return this.match(r.types.colon)?(i._exprListItem=!0,i.expression=n,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")):n}}),t.extend("checkLVal",function(t){return function(e){return"TypeCastExpression"!==e.type?t.apply(this,arguments):void 0}}),t.extend("parseClassProperty",function(t){return function(e){return this.match(r.types.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),t.call(this,e)}}),t.extend("isClassProperty",function(t){return function(){return this.match(r.types.colon)||t.call(this)}}),t.extend("parseClassMethod",function(){return function(t,e,s,i){this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.parseMethod(e,s,i),t.body.push(this.finishNode(e,"ClassMethod"))}}),t.extend("parseClassSuper",function(t){return function(e,s){if(t.call(this,e,s),e.superClass&&this.isRelational("<")&&(e.superTypeParameters=this.flowParseTypeParameterInstantiation()),this.isContextual("implements")){this.next();var i=e["implements"]=[];do{var n=this.startNode();n.id=this.parseIdentifier(),this.isRelational("<")?n.typeParameters=this.flowParseTypeParameterInstantiation():n.typeParameters=null,i.push(this.finishNode(n,"ClassImplements"))}while(this.eat(r.types.comma))}}}),t.extend("parseObjPropValue",function(t){return function(e){var s=void 0;this.isRelational("<")&&(s=this.flowParseTypeParameterDeclaration(),this.match(r.types.parenL)||this.unexpected()),t.apply(this,arguments),s&&((e.value||e).typeParameters=s)}}),t.extend("parseAssignableListItemTypes",function(){return function(t){return this.eat(r.types.question)&&(t.optional=!0),this.match(r.types.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),this.finishNode(t,t.type),t}}),t.extend("parseImportSpecifiers",function(t){return function(e){e.importKind="value";var s=null;if(this.match(r.types._typeof)?s="typeof":this.isContextual("type")&&(s="type"),s){var i=this.lookahead();(i.type===r.types.name&&"from"!==i.value||i.type===r.types.braceL||i.type===r.types.star)&&(this.next(),e.importKind=s)}t.call(this,e)}}),t.extend("parseFunctionParams",function(t){return function(e){this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),t.call(this,e)}}),t.extend("parseVarHead",function(t){return function(e){t.call(this,e),this.match(r.types.colon)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e.id,e.id.type))}}),t.extend("parseAsyncArrowFromCallExpression",function(t){return function(e,s){return this.match(r.types.colon)&&(e.returnType=this.flowParseTypeAnnotation()),t.call(this,e,s)}}),t.extend("shouldParseAsyncArrow",function(t){return function(){return this.match(r.types.colon)||t.call(this)}}),t.extend("parseParenAndDistinguishExpression",function(t){return function(e,s,i,n){if(e=e||this.state.start,s=s||this.state.startLoc,i&&this.lookahead().type===r.types.parenR){this.expect(r.types.parenL),this.expect(r.types.parenR);var a=this.startNodeAt(e,s);return this.match(r.types.colon)&&(a.returnType=this.flowParseTypeAnnotation()),this.expect(r.types.arrow),this.parseArrowExpression(a,[],n)}var a=t.call(this,e,s,i,n);if(!this.match(r.types.colon))return a;var o=this.state.clone();try{return this.parseParenItem(a,e,s,!0)}catch(u){if(u instanceof SyntaxError)return this.state=o,a;throw u}}})},e.exports=s["default"]},{"../parser":5,"../tokenizer/types":26,"babel-runtime/helpers/interop-require-default":35}],21:[function(t,e,s){"use strict";function i(t){return"JSXIdentifier"===t.type?t.name:"JSXNamespacedName"===t.type?t.namespace.name+":"+t.name.name:"JSXMemberExpression"===t.type?i(t.object)+"."+i(t.property):void 0}var r=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var n=t("./xhtml"),a=r(n),o=t("../../tokenizer/types"),u=t("../../tokenizer/context"),p=t("../../parser"),c=r(p),l=t("../../util/identifier"),h=t("../../util/whitespace"),f=/^[\da-fA-F]+$/,d=/^\d+$/;u.types.j_oTag=new u.TokContext("<tag",!1),u.types.j_cTag=new u.TokContext("</tag",!1),u.types.j_expr=new u.TokContext("<tag>...</tag>",!0,!0),o.types.jsxName=new o.TokenType("jsxName"),o.types.jsxText=new o.TokenType("jsxText",{beforeExpr:!0}),o.types.jsxTagStart=new o.TokenType("jsxTagStart"),o.types.jsxTagEnd=new o.TokenType("jsxTagEnd"),o.types.jsxTagStart.updateContext=function(){this.state.context.push(u.types.j_expr),this.state.context.push(u.types.j_oTag),this.state.exprAllowed=!1},o.types.jsxTagEnd.updateContext=function(t){var e=this.state.context.pop();e===u.types.j_oTag&&t===o.types.slash||e===u.types.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===u.types.j_expr):this.state.exprAllowed=!0};var y=c["default"].prototype;y.jsxReadToken=function(){for(var t="",e=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated JSX contents");var s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:return this.state.pos===this.state.start?60===s&&this.state.exprAllowed?(++this.state.pos,this.finishToken(o.types.jsxTagStart)):this.getTokenFromCode(s):(t+=this.input.slice(e,this.state.pos),this.finishToken(o.types.jsxText,t));case 38:t+=this.input.slice(e,this.state.pos),t+=this.jsxReadEntity(),e=this.state.pos;break;default:h.isNewLine(s)?(t+=this.input.slice(e,this.state.pos),t+=this.jsxReadNewLine(!0),e=this.state.pos):++this.state.pos}}},y.jsxReadNewLine=function(t){var e=this.input.charCodeAt(this.state.pos),s=void 0;return++this.state.pos,13===e&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,s=t?"\n":"\r\n"):s=String.fromCharCode(e),++this.state.curLine,this.state.lineStart=this.state.pos,s},y.jsxReadString=function(t){for(var e="",s=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var i=this.input.charCodeAt(this.state.pos);if(i===t)break;38===i?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadEntity(),s=this.state.pos):h.isNewLine(i)?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}return e+=this.input.slice(s,this.state.pos++),this.finishToken(o.types.string,e)},y.jsxReadEntity=function(){for(var t="",e=0,s=void 0,i=this.input[this.state.pos],r=++this.state.pos;this.state.pos<this.input.length&&e++<10;){if(i=this.input[this.state.pos++],";"===i){"#"===t[0]?"x"===t[1]?(t=t.substr(2),f.test(t)&&(s=String.fromCharCode(parseInt(t,16)))):(t=t.substr(1),d.test(t)&&(s=String.fromCharCode(parseInt(t,10)))):s=a["default"][t];break}t+=i}return s?s:(this.state.pos=r,"&")},y.jsxReadWord=function(){var t=void 0,e=this.state.pos;do t=this.input.charCodeAt(++this.state.pos);while(l.isIdentifierChar(t)||45===t);return this.finishToken(o.types.jsxName,this.input.slice(e,this.state.pos))},y.jsxParseIdentifier=function(){var t=this.startNode();return this.match(o.types.jsxName)?t.name=this.state.value:this.state.type.keyword?t.name=this.state.type.keyword:this.unexpected(),this.next(),this.finishNode(t,"JSXIdentifier")},y.jsxParseNamespacedName=function(){var t=this.state.start,e=this.state.startLoc,s=this.jsxParseIdentifier();if(!this.eat(o.types.colon))return s;var i=this.startNodeAt(t,e);return i.namespace=s,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")},y.jsxParseElementName=function(){for(var t=this.state.start,e=this.state.startLoc,s=this.jsxParseNamespacedName();this.eat(o.types.dot);){var i=this.startNodeAt(t,e);i.object=s,i.property=this.jsxParseIdentifier(),s=this.finishNode(i,"JSXMemberExpression")}return s},y.jsxParseAttributeValue=function(){var t=void 0;switch(this.state.type){case o.types.braceL:if(t=this.jsxParseExpressionContainer(),"JSXEmptyExpression"!==t.expression.type)return t;this.raise(t.start,"JSX attributes must only be assigned a non-empty expression");case o.types.jsxTagStart:case o.types.string:return t=this.parseExprAtom(),t.extra=null,t;default:this.raise(this.state.start,"JSX value should be either an expression or a quoted JSX text")}},y.jsxParseEmptyExpression=function(){var t=this.startNodeAt(this.lastTokEnd,this.lastTokEndLoc);return this.finishNodeAt(t,"JSXEmptyExpression",this.start,this.startLoc)},y.jsxParseExpressionContainer=function(){var t=this.startNode();return this.next(),this.match(o.types.braceR)?t.expression=this.jsxParseEmptyExpression():t.expression=this.parseExpression(),this.expect(o.types.braceR),this.finishNode(t,"JSXExpressionContainer")},y.jsxParseAttribute=function(){var t=this.startNode();return this.eat(o.types.braceL)?(this.expect(o.types.ellipsis),t.argument=this.parseMaybeAssign(),this.expect(o.types.braceR),this.finishNode(t,"JSXSpreadAttribute")):(t.name=this.jsxParseNamespacedName(),t.value=this.eat(o.types.eq)?this.jsxParseAttributeValue():null,this.finishNode(t,"JSXAttribute"))},y.jsxParseOpeningElementAt=function(t,e){var s=this.startNodeAt(t,e);for(s.attributes=[],s.name=this.jsxParseElementName();!this.match(o.types.slash)&&!this.match(o.types.jsxTagEnd);)s.attributes.push(this.jsxParseAttribute());return s.selfClosing=this.eat(o.types.slash),this.expect(o.types.jsxTagEnd),this.finishNode(s,"JSXOpeningElement")},y.jsxParseClosingElementAt=function(t,e){var s=this.startNodeAt(t,e);return s.name=this.jsxParseElementName(),this.expect(o.types.jsxTagEnd),this.finishNode(s,"JSXClosingElement")},y.jsxParseElementAt=function(t,e){var s=this.startNodeAt(t,e),r=[],n=this.jsxParseOpeningElementAt(t,e),a=null;if(!n.selfClosing){t:for(;;)switch(this.state.type){case o.types.jsxTagStart:if(t=this.state.start,e=this.state.startLoc,this.next(),this.eat(o.types.slash)){a=this.jsxParseClosingElementAt(t,e);break t}r.push(this.jsxParseElementAt(t,e));break;case o.types.jsxText:r.push(this.parseExprAtom());break;case o.types.braceL:r.push(this.jsxParseExpressionContainer());break;default:this.unexpected()}i(a.name)!==i(n.name)&&this.raise(a.start,"Expected corresponding JSX closing tag for <"+i(n.name)+">")}return s.openingElement=n,s.closingElement=a,s.children=r,this.match(o.types.relational)&&"<"===this.state.value&&this.raise(this.state.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(s,"JSXElement")},y.jsxParseElement=function(){var t=this.state.start,e=this.state.startLoc;return this.next(),this.jsxParseElementAt(t,e)},s["default"]=function(t){t.extend("parseExprAtom",function(t){return function(e){if(this.match(o.types.jsxText)){var s=this.parseLiteral(this.state.value,"JSXText");return s.extra=null,s}return this.match(o.types.jsxTagStart)?this.jsxParseElement():t.call(this,e)}}),t.extend("readToken",function(t){return function(e){var s=this.curContext();if(s===u.types.j_expr)return this.jsxReadToken();if(s===u.types.j_oTag||s===u.types.j_cTag){if(l.isIdentifierStart(e))return this.jsxReadWord();if(62===e)return++this.state.pos,this.finishToken(o.types.jsxTagEnd);if((34===e||39===e)&&s===u.types.j_oTag)return this.jsxReadString(e)}return 60===e&&this.state.exprAllowed?(++this.state.pos,this.finishToken(o.types.jsxTagStart)):t.call(this,e)}}),t.extend("updateContext",function(t){return function(e){if(this.match(o.types.braceL)){var s=this.curContext();s===u.types.j_oTag?this.state.context.push(u.types.b_expr):s===u.types.j_expr?this.state.context.push(u.types.b_tmpl):t.call(this,e),this.state.exprAllowed=!0}else{if(!this.match(o.types.slash)||e!==o.types.jsxTagStart)return t.call(this,e);this.state.context.length-=2,this.state.context.push(u.types.j_cTag),this.state.exprAllowed=!1}}})},e.exports=s["default"]},{"../../parser":5,"../../tokenizer/context":23,"../../tokenizer/types":26, "../../util/identifier":27,"../../util/whitespace":29,"./xhtml":22,"babel-runtime/helpers/interop-require-default":35}],22:[function(t,e,s){"use strict";s.__esModule=!0,s["default"]={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},e.exports=s["default"]},{}],23:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0;var r=t("./types"),n=t("../util/whitespace"),a=function u(t,e,s,r){i(this,u),this.token=t,this.isExpr=!!e,this.preserveSpace=!!s,this.override=r};s.TokContext=a;var o={b_stat:new a("{",!1),b_expr:new a("{",!0),b_tmpl:new a("${",!0),p_stat:new a("(",!1),p_expr:new a("(",!0),q_tmpl:new a("`",!0,!0,function(t){return t.readTmplToken()}),f_expr:new a("function",!0)};s.types=o,r.types.parenR.updateContext=r.types.braceR.updateContext=function(){if(1===this.state.context.length)return void(this.state.exprAllowed=!0);var t=this.state.context.pop();t===o.b_stat&&this.curContext()===o.f_expr?(this.state.context.pop(),this.state.exprAllowed=!1):t===o.b_tmpl?this.state.exprAllowed=!0:this.state.exprAllowed=!t.isExpr},r.types.name.updateContext=function(t){this.state.exprAllowed=!1,(t===r.types._let||t===r.types._const||t===r.types._var)&&n.lineBreak.test(this.input.slice(this.state.end))&&(this.state.exprAllowed=!0)},r.types.braceL.updateContext=function(t){this.state.context.push(this.braceIsBlock(t)?o.b_stat:o.b_expr),this.state.exprAllowed=!0},r.types.dollarBraceL.updateContext=function(){this.state.context.push(o.b_tmpl),this.state.exprAllowed=!0},r.types.parenL.updateContext=function(t){var e=t===r.types._if||t===r.types._for||t===r.types._with||t===r.types._while;this.state.context.push(e?o.p_stat:o.p_expr),this.state.exprAllowed=!0},r.types.incDec.updateContext=function(){},r.types._function.updateContext=function(){this.curContext()!==o.b_stat&&this.state.context.push(o.f_expr),this.state.exprAllowed=!1},r.types.backQuote.updateContext=function(){this.curContext()===o.q_tmpl?this.state.context.pop():this.state.context.push(o.q_tmpl),this.state.exprAllowed=!1}},{"../util/whitespace":29,"./types":26,"babel-runtime/helpers/class-call-check":33}],24:[function(t,e,s){"use strict";function i(t){return 65535>=t?String.fromCharCode(t):String.fromCharCode((t-65536>>10)+55296,(t-65536&1023)+56320)}var r=t("babel-runtime/helpers/class-call-check")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var a=t("../util/identifier"),o=t("./types"),u=t("./context"),p=t("../util/location"),c=t("../util/whitespace"),l=t("./state"),h=n(l),f=function y(t){r(this,y),this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new p.SourceLocation(t.startLoc,t.endLoc)};s.Token=f;var d=function(){function t(e,s){r(this,t),this.state=new h["default"],this.state.init(e,s)}return t.prototype.next=function(){this.isLookahead||this.state.tokens.push(new f(this.state)),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},t.prototype.eat=function(t){return this.match(t)?(this.next(),!0):!1},t.prototype.match=function(t){return this.state.type===t},t.prototype.isKeyword=function(t){return a.isKeyword(t)},t.prototype.lookahead=function(){var t=this.state;this.state=t.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;var e=this.state.clone(!0);return this.state=t,e},t.prototype.setStrict=function(t){if(this.state.strict=t,this.match(o.types.num)||this.match(o.types.string)){for(this.state.pos=this.state.start;this.state.pos<this.state.lineStart;)this.state.lineStart=this.input.lastIndexOf("\n",this.state.lineStart-2)+1,--this.state.curLine;this.nextToken()}},t.prototype.curContext=function(){return this.state.context[this.state.context.length-1]},t.prototype.nextToken=function(){var t=this.curContext();return t&&t.preserveSpace||this.skipSpace(),this.state.containsOctal=!1,this.state.octalPosition=null,this.state.start=this.state.pos,this.state.startLoc=this.state.curPosition(),this.state.pos>=this.input.length?this.finishToken(o.types.eof):t.override?t.override(this):this.readToken(this.fullCharCodeAtPos())},t.prototype.readToken=function(t){return a.isIdentifierStart(t)||92===t?this.readWord():this.getTokenFromCode(t)},t.prototype.fullCharCodeAtPos=function(){var t=this.input.charCodeAt(this.state.pos);if(55295>=t||t>=57344)return t;var e=this.input.charCodeAt(this.state.pos+1);return(t<<10)+e-56613888},t.prototype.pushComment=function(t,e,s,i,r,n){var a={type:t?"CommentBlock":"CommentLine",value:e,start:s,end:i,loc:new p.SourceLocation(r,n)};this.isLookahead||(this.state.tokens.push(a),this.state.comments.push(a)),this.addComment(a)},t.prototype.skipBlockComment=function(){var t=this.state.curPosition(),e=this.state.pos,s=this.input.indexOf("*/",this.state.pos+=2);-1===s&&this.raise(this.state.pos-2,"Unterminated comment"),this.state.pos=s+2,c.lineBreakG.lastIndex=e;for(var i=void 0;(i=c.lineBreakG.exec(this.input))&&i.index<this.state.pos;)++this.state.curLine,this.state.lineStart=i.index+i[0].length;this.pushComment(!0,this.input.slice(e+2,s),e,this.state.pos,t,this.state.curPosition())},t.prototype.skipLineComment=function(t){for(var e=this.state.pos,s=this.state.curPosition(),i=this.input.charCodeAt(this.state.pos+=t);this.state.pos<this.input.length&&10!==i&&13!==i&&8232!==i&&8233!==i;)++this.state.pos,i=this.input.charCodeAt(this.state.pos);this.pushComment(!1,this.input.slice(e+t,this.state.pos),e,this.state.pos,s,this.state.curPosition())},t.prototype.skipSpace=function(){t:for(;this.state.pos<this.input.length;){var t=this.input.charCodeAt(this.state.pos);switch(t){case 32:case 160:++this.state.pos;break;case 13:10===this.input.charCodeAt(this.state.pos+1)&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break t}break;default:if(!(t>8&&14>t||t>=5760&&c.nonASCIIwhitespace.test(String.fromCharCode(t))))break t;++this.state.pos}}},t.prototype.finishToken=function(t,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var s=this.state.type;this.state.type=t,this.state.value=e,this.updateContext(s)},t.prototype.readToken_dot=function(){var t=this.input.charCodeAt(this.state.pos+1);if(t>=48&&57>=t)return this.readNumber(!0);var e=this.input.charCodeAt(this.state.pos+2);return 46===t&&46===e?(this.state.pos+=3,this.finishToken(o.types.ellipsis)):(++this.state.pos,this.finishToken(o.types.dot))},t.prototype.readToken_slash=function(){if(this.state.exprAllowed)return++this.state.pos,this.readRegexp();var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(o.types.assign,2):this.finishOp(o.types.slash,1)},t.prototype.readToken_mult_modulo=function(t){var e=42===t?o.types.star:o.types.modulo,s=1,i=this.input.charCodeAt(this.state.pos+1);return 42===i&&this.hasPlugin("exponentiationOperator")&&(s++,i=this.input.charCodeAt(this.state.pos+2),e=o.types.exponent),61===i&&(s++,e=o.types.assign),this.finishOp(e,s)},t.prototype.readToken_pipe_amp=function(t){var e=this.input.charCodeAt(this.state.pos+1);return e===t?this.finishOp(124===t?o.types.logicalOR:o.types.logicalAND,2):61===e?this.finishOp(o.types.assign,2):this.finishOp(124===t?o.types.bitwiseOR:o.types.bitwiseAND,1)},t.prototype.readToken_caret=function(){var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(o.types.assign,2):this.finishOp(o.types.bitwiseXOR,1)},t.prototype.readToken_plus_min=function(t){var e=this.input.charCodeAt(this.state.pos+1);return e===t?45===e&&62===this.input.charCodeAt(this.state.pos+2)&&c.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(o.types.incDec,2):61===e?this.finishOp(o.types.assign,2):this.finishOp(o.types.plusMin,1)},t.prototype.readToken_lt_gt=function(t){var e=this.input.charCodeAt(this.state.pos+1),s=1;return e===t?(s=62===t&&62===this.input.charCodeAt(this.state.pos+2)?3:2,61===this.input.charCodeAt(this.state.pos+s)?this.finishOp(o.types.assign,s+1):this.finishOp(o.types.bitShift,s)):33===e&&60===t&&45===this.input.charCodeAt(this.state.pos+2)&&45===this.input.charCodeAt(this.state.pos+3)?(this.inModule&&this.unexpected(),this.skipLineComment(4),this.skipSpace(),this.nextToken()):(61===e&&(s=61===this.input.charCodeAt(this.state.pos+2)?3:2),this.finishOp(o.types.relational,s))},t.prototype.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.state.pos+1);return 61===e?this.finishOp(o.types.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2):61===t&&62===e?(this.state.pos+=2,this.finishToken(o.types.arrow)):this.finishOp(61===t?o.types.eq:o.types.prefix,1)},t.prototype.getTokenFromCode=function(t){switch(t){case 46:return this.readToken_dot();case 40:return++this.state.pos,this.finishToken(o.types.parenL);case 41:return++this.state.pos,this.finishToken(o.types.parenR);case 59:return++this.state.pos,this.finishToken(o.types.semi);case 44:return++this.state.pos,this.finishToken(o.types.comma);case 91:return++this.state.pos,this.finishToken(o.types.bracketL);case 93:return++this.state.pos,this.finishToken(o.types.bracketR);case 123:return++this.state.pos,this.finishToken(o.types.braceL);case 125:return++this.state.pos,this.finishToken(o.types.braceR);case 58:return this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(o.types.doubleColon,2):(++this.state.pos,this.finishToken(o.types.colon));case 63:return++this.state.pos,this.finishToken(o.types.question);case 64:return++this.state.pos,this.finishToken(o.types.at);case 96:return++this.state.pos,this.finishToken(o.types.backQuote);case 48:var e=this.input.charCodeAt(this.state.pos+1);if(120===e||88===e)return this.readRadixNumber(16);if(111===e||79===e)return this.readRadixNumber(8);if(98===e||66===e)return this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(t);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo(t);case 124:case 38:return this.readToken_pipe_amp(t);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(t);case 60:case 62:return this.readToken_lt_gt(t);case 61:case 33:return this.readToken_eq_excl(t);case 126:return this.finishOp(o.types.prefix,1)}this.raise(this.state.pos,"Unexpected character '"+i(t)+"'")},t.prototype.finishOp=function(t,e){var s=this.input.slice(this.state.pos,this.state.pos+e);return this.state.pos+=e,this.finishToken(t,s)},t.prototype.readRegexp=function(){for(var t=void 0,e=void 0,s=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var i=this.input.charAt(this.state.pos);if(c.lineBreak.test(i)&&this.raise(s,"Unterminated regular expression"),t)t=!1;else{if("["===i)e=!0;else if("]"===i&&e)e=!1;else if("/"===i&&!e)break;t="\\"===i}++this.state.pos}var r=this.input.slice(s,this.state.pos);++this.state.pos;var n=this.readWord1();if(n){var a=/^[gmsiyu]*$/;a.test(n)||this.raise(s,"Invalid regular expression flag")}return this.finishToken(o.types.regexp,{pattern:r,flags:n})},t.prototype.readInt=function(t,e){for(var s=this.state.pos,i=0,r=0,n=null==e?1/0:e;n>r;++r){var a=this.input.charCodeAt(this.state.pos),o=void 0;if(o=a>=97?a-97+10:a>=65?a-65+10:a>=48&&57>=a?a-48:1/0,o>=t)break;++this.state.pos,i=i*t+o}return this.state.pos===s||null!=e&&this.state.pos-s!==e?null:i},t.prototype.readRadixNumber=function(t){this.state.pos+=2;var e=this.readInt(t);return null==e&&this.raise(this.state.start+2,"Expected number in radix "+t),a.isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number"),this.finishToken(o.types.num,e)},t.prototype.readNumber=function(t){var e=this.state.pos,s=!1,i=48===this.input.charCodeAt(this.state.pos);t||null!==this.readInt(10)||this.raise(e,"Invalid number");var r=this.input.charCodeAt(this.state.pos);46===r&&(++this.state.pos,this.readInt(10),s=!0,r=this.input.charCodeAt(this.state.pos)),(69===r||101===r)&&(r=this.input.charCodeAt(++this.state.pos),(43===r||45===r)&&++this.state.pos,null===this.readInt(10)&&this.raise(e,"Invalid number"),s=!0),a.isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number");var n=this.input.slice(e,this.state.pos),u=void 0;return s?u=parseFloat(n):i&&1!==n.length?/[89]/.test(n)||this.state.strict?this.raise(e,"Invalid number"):u=parseInt(n,8):u=parseInt(n,10),this.finishToken(o.types.num,u)},t.prototype.readCodePoint=function(){var t=this.input.charCodeAt(this.state.pos),e=void 0;if(123===t){var s=++this.state.pos;e=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos),++this.state.pos,e>1114111&&this.raise(s,"Code point out of bounds")}else e=this.readHexChar(4);return e},t.prototype.readString=function(t){for(var e="",s=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var i=this.input.charCodeAt(this.state.pos);if(i===t)break;92===i?(e+=this.input.slice(s,this.state.pos),e+=this.readEscapedChar(!1),s=this.state.pos):(c.isNewLine(i)&&this.raise(this.state.start,"Unterminated string constant"),++this.state.pos)}return e+=this.input.slice(s,this.state.pos++),this.finishToken(o.types.string,e)},t.prototype.readTmplToken=function(){for(var t="",e=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated template");var s=this.input.charCodeAt(this.state.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(o.types.template)?36===s?(this.state.pos+=2,this.finishToken(o.types.dollarBraceL)):(++this.state.pos,this.finishToken(o.types.backQuote)):(t+=this.input.slice(e,this.state.pos),this.finishToken(o.types.template,t));if(92===s)t+=this.input.slice(e,this.state.pos),t+=this.readEscapedChar(!0),e=this.state.pos;else if(c.isNewLine(s)){switch(t+=this.input.slice(e,this.state.pos),++this.state.pos,s){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:t+="\n";break;default:t+=String.fromCharCode(s)}++this.state.curLine,this.state.lineStart=this.state.pos,e=this.state.pos}else++this.state.pos}},t.prototype.readEscapedChar=function(t){var e=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,e){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return i(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\x0B";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:return this.state.lineStart=this.state.pos,++this.state.curLine,"";default:if(e>=48&&55>=e){var s=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],r=parseInt(s,8);return r>255&&(s=s.slice(0,-1),r=parseInt(s,8)),r>0&&(this.state.containsOctal||(this.state.containsOctal=!0,this.state.octalPosition=this.state.pos-2),(this.state.strict||t)&&this.raise(this.state.pos-2,"Octal literal in strict mode")),this.state.pos+=s.length-1,String.fromCharCode(r)}return String.fromCharCode(e)}},t.prototype.readHexChar=function(t){var e=this.state.pos,s=this.readInt(16,t);return null===s&&this.raise(e,"Bad character escape sequence"),s},t.prototype.readWord1=function(){this.state.containsEsc=!1;for(var t="",e=!0,s=this.state.pos;this.state.pos<this.input.length;){var r=this.fullCharCodeAtPos();if(a.isIdentifierChar(r))this.state.pos+=65535>=r?1:2;else{if(92!==r)break;this.state.containsEsc=!0,t+=this.input.slice(s,this.state.pos);var n=this.state.pos;117!==this.input.charCodeAt(++this.state.pos)&&this.raise(this.state.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.state.pos;var o=this.readCodePoint();(e?a.isIdentifierStart:a.isIdentifierChar)(o,!0)||this.raise(n,"Invalid Unicode escape"),t+=i(o),s=this.state.pos}e=!1}return t+this.input.slice(s,this.state.pos)},t.prototype.readWord=function(){var t=this.readWord1(),e=o.types.name;return!this.state.containsEsc&&this.isKeyword(t)&&(e=o.keywords[t]),this.finishToken(e,t)},t.prototype.braceIsBlock=function(t){if(t===o.types.colon){var e=this.curContext();if(e===u.types.b_stat||e===u.types.b_expr)return!e.isExpr}return t===o.types._return?c.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.start)):t===o.types._else||t===o.types.semi||t===o.types.eof||t===o.types.parenR?!0:t===o.types.braceL?this.curContext()===u.types.b_stat:!this.state.exprAllowed},t.prototype.updateContext=function(t){var e=void 0,s=this.state.type;s.keyword&&t===o.types.dot?this.state.exprAllowed=!1:(e=s.updateContext)?e.call(this,t):this.state.exprAllowed=s.beforeExpr},t}();s["default"]=d},{"../util/identifier":27,"../util/location":28,"../util/whitespace":29,"./context":23,"./state":25,"./types":26,"babel-runtime/helpers/class-call-check":33,"babel-runtime/helpers/interop-require-default":35}],25:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0;var r=t("../util/location"),n=t("./context"),a=t("./types"),o=function(){function t(){i(this,t)}return t.prototype.init=function(t,e){return this.strict=t.strictMode===!1?!1:"module"===t.sourceType,this.input=e,this.potentialArrowAt=-1,this.inMethod=this.inFunction=this.inGenerator=this.inAsync=!1,this.labels=[],this.decorators=[],this.tokens=[],this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.pos=this.lineStart=0,this.curLine=1,this.type=a.types.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=[n.types.b_stat],this.exprAllowed=!0,this.containsEsc=this.containsOctal=!1,this.octalPosition=null,this},t.prototype.curPosition=function(){return new r.Position(this.curLine,this.pos-this.lineStart)},t.prototype.clone=function(e){var s=new t;for(var i in this){var r=this[i];e&&"context"!==i||!Array.isArray(r)||(r=r.slice()),s[i]=r}return s},t}();s["default"]=o,e.exports=s["default"]},{"../util/location":28,"./context":23,"./types":26,"babel-runtime/helpers/class-call-check":33}],26:[function(t,e,s){"use strict";function i(t,e){return new a(t,{beforeExpr:!0,binop:e})}function r(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];e.keyword=t,c[t]=p["_"+t]=new a(t,e)}var n=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0;var a=function l(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];n(this,l),this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop||null,this.updateContext=null};s.TokenType=a;var o={beforeExpr:!0},u={startsExpr:!0},p={num:new a("num",u),regexp:new a("regexp",u),string:new a("string",u),name:new a("name",u),eof:new a("eof"),bracketL:new a("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new a("]"),braceL:new a("{",{beforeExpr:!0,startsExpr:!0}),braceR:new a("}"),parenL:new a("(",{beforeExpr:!0,startsExpr:!0}),parenR:new a(")"),comma:new a(",",o),semi:new a(";",o),colon:new a(":",o),doubleColon:new a("::",o),dot:new a("."),question:new a("?",o),arrow:new a("=>",o),template:new a("template"),ellipsis:new a("...",o),backQuote:new a("`",u),dollarBraceL:new a("${",{beforeExpr:!0,startsExpr:!0}),at:new a("@"),eq:new a("=",{beforeExpr:!0,isAssign:!0}),assign:new a("_=",{beforeExpr:!0,isAssign:!0}),incDec:new a("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new a("prefix",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:i("||",1),logicalAND:i("&&",2),bitwiseOR:i("|",3),bitwiseXOR:i("^",4),bitwiseAND:i("&",5),equality:i("==/!=",6),relational:i("</>",7),bitShift:i("<</>>",8),plusMin:new a("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:i("%",10),star:i("*",10),slash:i("/",10),exponent:new a("**",{beforeExpr:!0,binop:11,rightAssociative:!0})};s.types=p;var c={};s.keywords=c,r("break"),r("case",o),r("catch"),r("continue"),r("debugger"),r("default",o),r("do",{isLoop:!0,beforeExpr:!0}),r("else",o),r("finally"),r("for",{isLoop:!0}),r("function",u),r("if"),r("return",o),r("switch"),r("throw",o),r("try"),r("var"),r("let"),r("const"),r("while",{isLoop:!0}),r("with"),r("new",{beforeExpr:!0,startsExpr:!0}),r("this",u),r("super",u),r("class"),r("extends",o),r("export"),r("import"),r("yield",{beforeExpr:!0,startsExpr:!0}),r("null",u),r("true",u),r("false",u),r("in",{beforeExpr:!0,binop:7}),r("instanceof",{beforeExpr:!0,binop:7}),r("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),r("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),r("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},{"babel-runtime/helpers/class-call-check":33}],27:[function(t,e,s){"use strict";function i(t){return t=t.split(" "),function(e){return t.indexOf(e)>=0}}function r(t,e){for(var s=65536,i=0;i<e.length;i+=2){if(s+=e[i],s>t)return!1;if(s+=e[i+1],s>=t)return!0}}function n(t){return 65>t?36===t:91>t?!0:97>t?95===t:123>t?!0:65535>=t?t>=170&&l.test(String.fromCharCode(t)):r(t,f)}function a(t){return 48>t?36===t:58>t?!0:65>t?!1:91>t?!0:97>t?95===t:123>t?!0:65535>=t?t>=170&&h.test(String.fromCharCode(t)):r(t,f)||r(t,d)}s.__esModule=!0,s.isIdentifierStart=n,s.isIdentifierChar=a;var o={6:i("enum await"),strict:i("implements interface let package private protected public static yield"),strictBind:i("eval arguments")};s.reservedWords=o;var u=i("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super");s.isKeyword=u;var p="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",c="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_",l=new RegExp("["+p+"]"),h=new RegExp("["+p+c+"]");p=c=null;var f=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,99,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,98,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,955,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,38,17,2,24,133,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,32,4,287,47,21,1,2,0,185,46,82,47,21,0,60,42,502,63,32,0,449,56,1288,920,104,110,2962,1070,13266,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,16481,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,1340,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,16355,541],d=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,16,9,83,11,168,11,6,9,8,2,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,316,19,13,9,214,6,3,8,112,16,16,9,82,12,9,9,535,9,20855,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,4305,6,792618,239]},{}],28:[function(t,e,s){"use strict";function i(t,e){for(var s=1,i=0;;){n.lineBreakG.lastIndex=i;var r=n.lineBreakG.exec(t);if(!(r&&r.index<e))return new a(s,e-i);++s,i=r.index+r[0].length}}var r=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0,s.getLineInfo=i;var n=t("./whitespace"),a=function u(t,e){r(this,u),this.line=t,this.column=e};s.Position=a;var o=function p(t,e){r(this,p),this.start=t,this.end=e};s.SourceLocation=o},{"./whitespace":29,"babel-runtime/helpers/class-call-check":33}],29:[function(t,e,s){"use strict";function i(t){return 10===t||13===t||8232===t||8233===t}s.__esModule=!0,s.isNewLine=i;var r=/\r\n?|\n|\u2028|\u2029/;s.lineBreak=r;var n=new RegExp(r.source,"g");s.lineBreakG=n;var a=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;s.nonASCIIwhitespace=a},{}],30:[function(t,e,s){e.exports={"default":t("core-js/library/fn/get-iterator"),__esModule:!0}},{"core-js/library/fn/get-iterator":36}],31:[function(t,e,s){e.exports={"default":t("core-js/library/fn/object/create"),__esModule:!0}},{"core-js/library/fn/object/create":37}],32:[function(t,e,s){e.exports={"default":t("core-js/library/fn/object/set-prototype-of"),__esModule:!0}},{"core-js/library/fn/object/set-prototype-of":38}],33:[function(t,e,s){"use strict";s["default"]=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},s.__esModule=!0},{}],34:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/object/create")["default"],r=t("babel-runtime/core-js/object/set-prototype-of")["default"];s["default"]=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=i(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(r?r(t,e):t.__proto__=e)},s.__esModule=!0},{"babel-runtime/core-js/object/create":31,"babel-runtime/core-js/object/set-prototype-of":32}],35:[function(t,e,s){"use strict";s["default"]=function(t){return t&&t.__esModule?t:{"default":t}},s.__esModule=!0},{}],36:[function(t,e,s){t("../modules/web.dom.iterable"),t("../modules/es6.string.iterator"),e.exports=t("../modules/core.get-iterator")},{"../modules/core.get-iterator":72,"../modules/es6.string.iterator":75,"../modules/web.dom.iterable":76}],37:[function(t,e,s){var i=t("../../modules/$");e.exports=function(t,e){return i.create(t,e)}},{"../../modules/$":59}],38:[function(t,e,s){t("../../modules/es6.object.set-prototype-of"),e.exports=t("../../modules/$.core").Object.setPrototypeOf},{"../../modules/$.core":44,"../../modules/es6.object.set-prototype-of":74}],39:[function(t,e,s){e.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},{}],40:[function(t,e,s){e.exports=function(){}},{}],41:[function(t,e,s){var i=t("./$.is-object");e.exports=function(t){if(!i(t))throw TypeError(t+" is not an object!");return t}},{"./$.is-object":54}],42:[function(t,e,s){var i=t("./$.cof"),r=t("./$.wks")("toStringTag"),n="Arguments"==i(function(){return arguments}());e.exports=function(t){var e,s,a;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(s=(e=Object(t))[r])?s:n?i(e):"Object"==(a=i(e))&&"function"==typeof e.callee?"Arguments":a}},{"./$.cof":43,"./$.wks":70}],43:[function(t,e,s){var i={}.toString;e.exports=function(t){return i.call(t).slice(8,-1)}},{}],44:[function(t,e,s){var i=e.exports={version:"1.2.6"};"number"==typeof __e&&(__e=i)},{}],45:[function(t,e,s){var i=t("./$.a-function");e.exports=function(t,e,s){if(i(t),void 0===e)return t;switch(s){case 1:return function(s){return t.call(e,s)};case 2:return function(s,i){return t.call(e,s,i)};case 3:return function(s,i,r){return t.call(e,s,i,r)}}return function(){return t.apply(e,arguments)}}},{"./$.a-function":39}],46:[function(t,e,s){e.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},{}],47:[function(t,e,s){e.exports=!t("./$.fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./$.fails":49}],48:[function(t,e,s){var i=t("./$.global"),r=t("./$.core"),n=t("./$.ctx"),a="prototype",o=function(t,e,s){var u,p,c,l=t&o.F,h=t&o.G,f=t&o.S,d=t&o.P,y=t&o.B,m=t&o.W,v=h?r:r[e]||(r[e]={}),g=h?i:f?i[e]:(i[e]||{})[a];h&&(s=e);for(u in s)p=!l&&g&&u in g,p&&u in v||(c=p?g[u]:s[u],v[u]=h&&"function"!=typeof g[u]?s[u]:y&&p?n(c,i):m&&g[u]==c?function(t){var e=function(e){return this instanceof t?new t(e):t(e)};return e[a]=t[a],e}(c):d&&"function"==typeof c?n(Function.call,c):c,d&&((v[a]||(v[a]={}))[u]=c))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,e.exports=o},{"./$.core":44,"./$.ctx":45,"./$.global":50}],49:[function(t,e,s){e.exports=function(t){try{return!!t()}catch(e){return!0}}},{}],50:[function(t,e,s){ var i=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=i)},{}],51:[function(t,e,s){var i={}.hasOwnProperty;e.exports=function(t,e){return i.call(t,e)}},{}],52:[function(t,e,s){var i=t("./$"),r=t("./$.property-desc");e.exports=t("./$.descriptors")?function(t,e,s){return i.setDesc(t,e,r(1,s))}:function(t,e,s){return t[e]=s,t}},{"./$":59,"./$.descriptors":47,"./$.property-desc":61}],53:[function(t,e,s){var i=t("./$.cof");e.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==i(t)?t.split(""):Object(t)}},{"./$.cof":43}],54:[function(t,e,s){e.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},{}],55:[function(t,e,s){"use strict";var i=t("./$"),r=t("./$.property-desc"),n=t("./$.set-to-string-tag"),a={};t("./$.hide")(a,t("./$.wks")("iterator"),function(){return this}),e.exports=function(t,e,s){t.prototype=i.create(a,{next:r(1,s)}),n(t,e+" Iterator")}},{"./$":59,"./$.hide":52,"./$.property-desc":61,"./$.set-to-string-tag":64,"./$.wks":70}],56:[function(t,e,s){"use strict";var i=t("./$.library"),r=t("./$.export"),n=t("./$.redefine"),a=t("./$.hide"),o=t("./$.has"),u=t("./$.iterators"),p=t("./$.iter-create"),c=t("./$.set-to-string-tag"),l=t("./$").getProto,h=t("./$.wks")("iterator"),f=!([].keys&&"next"in[].keys()),d="@@iterator",y="keys",m="values",v=function(){return this};e.exports=function(t,e,s,g,x,A,b){p(s,e,g);var E,C,D=function(t){if(!f&&t in T)return T[t];switch(t){case y:return function(){return new s(this,t)};case m:return function(){return new s(this,t)}}return function(){return new s(this,t)}},S=e+" Iterator",F=x==m,w=!1,T=t.prototype,k=T[h]||T[d]||x&&T[x],P=k||D(x);if(k){var _=l(P.call(new t));c(_,S,!0),!i&&o(T,d)&&a(_,h,v),F&&k.name!==m&&(w=!0,P=function(){return k.call(this)})}if(i&&!b||!f&&!w&&T[h]||a(T,h,P),u[e]=P,u[S]=v,x)if(E={values:F?P:D(m),keys:A?P:D(y),entries:F?D("entries"):P},b)for(C in E)C in T||n(T,C,E[C]);else r(r.P+r.F*(f||w),e,E);return E}},{"./$":59,"./$.export":48,"./$.has":51,"./$.hide":52,"./$.iter-create":55,"./$.iterators":58,"./$.library":60,"./$.redefine":62,"./$.set-to-string-tag":64,"./$.wks":70}],57:[function(t,e,s){e.exports=function(t,e){return{value:e,done:!!t}}},{}],58:[function(t,e,s){e.exports={}},{}],59:[function(t,e,s){var i=Object;e.exports={create:i.create,getProto:i.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:i.getOwnPropertyDescriptor,setDesc:i.defineProperty,setDescs:i.defineProperties,getKeys:i.keys,getNames:i.getOwnPropertyNames,getSymbols:i.getOwnPropertySymbols,each:[].forEach}},{}],60:[function(t,e,s){e.exports=!0},{}],61:[function(t,e,s){e.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},{}],62:[function(t,e,s){e.exports=t("./$.hide")},{"./$.hide":52}],63:[function(t,e,s){var i=t("./$").getDesc,r=t("./$.is-object"),n=t("./$.an-object"),a=function(t,e){if(n(t),!r(e)&&null!==e)throw TypeError(e+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,s,r){try{r=t("./$.ctx")(Function.call,i(Object.prototype,"__proto__").set,2),r(e,[]),s=!(e instanceof Array)}catch(n){s=!0}return function(t,e){return a(t,e),s?t.__proto__=e:r(t,e),t}}({},!1):void 0),check:a}},{"./$":59,"./$.an-object":41,"./$.ctx":45,"./$.is-object":54}],64:[function(t,e,s){var i=t("./$").setDesc,r=t("./$.has"),n=t("./$.wks")("toStringTag");e.exports=function(t,e,s){t&&!r(t=s?t:t.prototype,n)&&i(t,n,{configurable:!0,value:e})}},{"./$":59,"./$.has":51,"./$.wks":70}],65:[function(t,e,s){var i=t("./$.global"),r="__core-js_shared__",n=i[r]||(i[r]={});e.exports=function(t){return n[t]||(n[t]={})}},{"./$.global":50}],66:[function(t,e,s){var i=t("./$.to-integer"),r=t("./$.defined");e.exports=function(t){return function(e,s){var n,a,o=String(r(e)),u=i(s),p=o.length;return 0>u||u>=p?t?"":void 0:(n=o.charCodeAt(u),55296>n||n>56319||u+1===p||(a=o.charCodeAt(u+1))<56320||a>57343?t?o.charAt(u):n:t?o.slice(u,u+2):(n-55296<<10)+(a-56320)+65536)}}},{"./$.defined":46,"./$.to-integer":67}],67:[function(t,e,s){var i=Math.ceil,r=Math.floor;e.exports=function(t){return isNaN(t=+t)?0:(t>0?r:i)(t)}},{}],68:[function(t,e,s){var i=t("./$.iobject"),r=t("./$.defined");e.exports=function(t){return i(r(t))}},{"./$.defined":46,"./$.iobject":53}],69:[function(t,e,s){var i=0,r=Math.random();e.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++i+r).toString(36))}},{}],70:[function(t,e,s){var i=t("./$.shared")("wks"),r=t("./$.uid"),n=t("./$.global").Symbol;e.exports=function(t){return i[t]||(i[t]=n&&n[t]||(n||r)("Symbol."+t))}},{"./$.global":50,"./$.shared":65,"./$.uid":69}],71:[function(t,e,s){var i=t("./$.classof"),r=t("./$.wks")("iterator"),n=t("./$.iterators");e.exports=t("./$.core").getIteratorMethod=function(t){return void 0!=t?t[r]||t["@@iterator"]||n[i(t)]:void 0}},{"./$.classof":42,"./$.core":44,"./$.iterators":58,"./$.wks":70}],72:[function(t,e,s){var i=t("./$.an-object"),r=t("./core.get-iterator-method");e.exports=t("./$.core").getIterator=function(t){var e=r(t);if("function"!=typeof e)throw TypeError(t+" is not iterable!");return i(e.call(t))}},{"./$.an-object":41,"./$.core":44,"./core.get-iterator-method":71}],73:[function(t,e,s){"use strict";var i=t("./$.add-to-unscopables"),r=t("./$.iter-step"),n=t("./$.iterators"),a=t("./$.to-iobject");e.exports=t("./$.iter-define")(Array,"Array",function(t,e){this._t=a(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,s=this._i++;return!t||s>=t.length?(this._t=void 0,r(1)):"keys"==e?r(0,s):"values"==e?r(0,t[s]):r(0,[s,t[s]])},"values"),n.Arguments=n.Array,i("keys"),i("values"),i("entries")},{"./$.add-to-unscopables":40,"./$.iter-define":56,"./$.iter-step":57,"./$.iterators":58,"./$.to-iobject":68}],74:[function(t,e,s){var i=t("./$.export");i(i.S,"Object",{setPrototypeOf:t("./$.set-proto").set})},{"./$.export":48,"./$.set-proto":63}],75:[function(t,e,s){"use strict";var i=t("./$.string-at")(!0);t("./$.iter-define")(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,s=this._i;return s>=e.length?{value:void 0,done:!0}:(t=i(e,s),this._i+=t.length,{value:t,done:!1})})},{"./$.iter-define":56,"./$.string-at":66}],76:[function(t,e,s){t("./es6.array.iterator");var i=t("./$.iterators");i.NodeList=i.HTMLCollection=i.Array},{"./$.iterators":58,"./es6.array.iterator":73}]},{},[1])(1)})},function(t,e,s){var i=s(4),r="start,end,loc",n="unknown",a=function(t){return r.indexOf(t)>=0},o=function(t){return t&&t.type?t.type:n};t.exports=function(t,e){var s={},r=function(t,n,u){var p,c,l=o(t),h=e[l];if(h&&h.enter?h.enter(t,n,u,s):null,i(t))for(c=0;c<t.length;c++)r(t[c],t,c);else for(p in t)a(p)||"object"==typeof t[p]&&r(t[p],t,p);h&&h.exit?h.exit(t,n,u,s):null};r(t,null,null)},t.exports.isIgnored=a},function(t,e){t.exports=function(t){return"[object Array]"===Object.prototype.toString.call(t)}},function(t,e,s){"use strict";var i=s(6)["default"],r=s(21)["default"],n=s(22)["default"],a=s(23)["default"];e.__esModule=!0;var o=s(24),u=n(o),p=s(28),c=n(p),l=s(29),h=n(l),f=s(272),d=n(f),y=s(273),m=a(y),v=s(274),g=n(v),x=function(t){function e(s,i,n){r(this,e),i=i||{};var a=s.comments||[],o=s.tokens||[],u=e.normalizeOptions(n,i,o),p=new d["default"];t.call(this,p,u),this.comments=a,this.position=p,this.tokens=o,this.format=u,this.opts=i,this.ast=s,this.whitespace=new c["default"](o),this.map=new h["default"](p,i,n)}return i(e,t),e.normalizeOptions=function(t,s,i){var r=" ";if(t){var n=u["default"](t).indent;n&&" "!==n&&(r=n)}var a={auxiliaryCommentBefore:s.auxiliaryCommentBefore,auxiliaryCommentAfter:s.auxiliaryCommentAfter,shouldPrintComment:s.shouldPrintComment,retainLines:s.retainLines,comments:null==s.comments||s.comments,compact:s.compact,minified:s.minified,concise:s.concise,quotes:s.quotes||e.findCommonStringDelimiter(t,i),indent:{adjustMultilineComment:!0,style:r,base:0}};return a.minified&&(a.compact=!0),"auto"===a.compact&&(a.compact=t.length>1e5,a.compact&&console.error("[BABEL] "+m.get("codeGeneratorDeopt",s.filename,"100KB"))),a.compact&&(a.indent.adjustMultilineComment=!1),a},e.findCommonStringDelimiter=function(t,e){for(var s={single:0,"double":0},i=0,r=0;r<e.length;r++){var n=e[r];if("string"===n.type.label){var a=t.slice(n.start,n.end);if("'"===a[0]?s.single++:s["double"]++,i++,i>=3)break}}return s.single>s["double"]?"single":"double"},e.prototype.generate=function(){return this.print(this.ast),this.printAuxAfterComment(),{map:this.map.get(),code:this.get()}},e}(g["default"]);e.CodeGenerator=x,e["default"]=function(t,e,s){var i=new x(t,e,s);return i.generate()}},function(t,e,s){"use strict";var i=s(7)["default"],r=s(10)["default"];e["default"]=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=i(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(r?r(t,e):t.__proto__=e)},e.__esModule=!0},function(t,e,s){t.exports={"default":s(8),__esModule:!0}},function(t,e,s){var i=s(9);t.exports=function(t,e){return i.create(t,e)}},function(t,e){var s=Object;t.exports={create:s.create,getProto:s.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:s.getOwnPropertyDescriptor,setDesc:s.defineProperty,setDescs:s.defineProperties,getKeys:s.keys,getNames:s.getOwnPropertyNames,getSymbols:s.getOwnPropertySymbols,each:[].forEach}},function(t,e,s){t.exports={"default":s(11),__esModule:!0}},function(t,e,s){s(12),t.exports=s(15).Object.setPrototypeOf},function(t,e,s){var i=s(13);i(i.S,"Object",{setPrototypeOf:s(18).set})},function(t,e,s){var i=s(14),r=s(15),n=s(16),a="prototype",o=function(t,e,s){var u,p,c,l=t&o.F,h=t&o.G,f=t&o.S,d=t&o.P,y=t&o.B,m=t&o.W,v=h?r:r[e]||(r[e]={}),g=h?i:f?i[e]:(i[e]||{})[a];h&&(s=e);for(u in s)p=!l&&g&&u in g,p&&u in v||(c=p?g[u]:s[u],v[u]=h&&"function"!=typeof g[u]?s[u]:y&&p?n(c,i):m&&g[u]==c?function(t){var e=function(e){return this instanceof t?new t(e):t(e)};return e[a]=t[a],e}(c):d&&"function"==typeof c?n(Function.call,c):c,d&&((v[a]||(v[a]={}))[u]=c))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,t.exports=o},function(t,e){var s=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=s)},function(t,e){var s=t.exports={version:"1.2.6"};"number"==typeof __e&&(__e=s)},function(t,e,s){var i=s(17);t.exports=function(t,e,s){if(i(t),void 0===e)return t;switch(s){case 1:return function(s){return t.call(e,s)};case 2:return function(s,i){return t.call(e,s,i)};case 3:return function(s,i,r){return t.call(e,s,i,r)}}return function(){return t.apply(e,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,s){var i=s(9).getDesc,r=s(19),n=s(20),a=function(t,e){if(n(t),!r(e)&&null!==e)throw TypeError(e+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(t,e,r){try{r=s(16)(Function.call,i(Object.prototype,"__proto__").set,2),r(t,[]),e=!(t instanceof Array)}catch(n){e=!0}return function(t,s){return a(t,s),e?t.__proto__=s:r(t,s),t}}({},!1):void 0),check:a}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,s){var i=s(19);t.exports=function(t){if(!i(t))throw TypeError(t+" is not an object!");return t}},function(t,e){"use strict";e["default"]=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},e.__esModule=!0},function(t,e){"use strict";e["default"]=function(t){return t&&t.__esModule?t:{"default":t}},e.__esModule=!0},function(t,e){"use strict";e["default"]=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e["default"]=t,e},e.__esModule=!0},function(t,e,s){"use strict";function i(t){var e=0,s=0,i=0;for(var r in t){var n=t[r],a=n[0],o=n[1];(a>s||a===s&&o>i)&&(s=a,i=o,e=+r)}return e}var r=s(25),n=/^(?:( )+|\t+)/;t.exports=function(t){if("string"!=typeof t)throw new TypeError("Expected a string");var e,s,a=0,o=0,u=0,p={};t.split(/\n/g).forEach(function(t){if(t){var i,r=t.match(n);r?(i=r[0].length,r[1]?o++:a++):i=0;var c=i-u;u=i,c?(s=c>0,e=p[s?c:-c],e?e[0]++:e=p[c]=[1,0]):e&&(e[1]+=+s)}});var c,l,h=i(p);return h?o>=a?(c="space",l=r(" ",h)):(c="tab",l=r(" ",h)):(c=null,l=""),{amount:h,type:c,indent:l}}},function(t,e,s){"use strict";var i=s(26);t.exports=function(t,e){if("string"!=typeof t)throw new TypeError("Expected a string as the first argument");if(0>e||!i(e))throw new TypeError("Expected a finite positive number");var s="";do 1&e&&(s+=t),t+=t;while(e>>=1);return s}},function(t,e,s){"use strict";var i=s(27);t.exports=Number.isFinite||function(t){return!("number"!=typeof t||i(t)||t===1/0||t===-(1/0))}},function(t,e){"use strict";t.exports=Number.isNaN||function(t){return t!==t}},function(t,e,s){"use strict";function i(t,e,s){return t+=e,t>=s&&(t-=s),t}var r=s(21)["default"];e.__esModule=!0;var n=function(){function t(e){r(this,t),this.tokens=e,this.used={},this._lastFoundIndex=0}return t.prototype.getNewlinesBefore=function(t){for(var e=void 0,s=void 0,r=this.tokens,n=0;n<r.length;n++){var a=i(n,this._lastFoundIndex,this.tokens.length),o=r[a];if(t.start===o.start){e=r[a-1],s=o,this._lastFoundIndex=a;break}}return this.getNewlinesBetween(e,s)},t.prototype.getNewlinesAfter=function(t){for(var e=void 0,s=void 0,r=this.tokens,n=0;n<r.length;n++){var a=i(n,this._lastFoundIndex,this.tokens.length),o=r[a];if(t.end===o.end){e=o,s=r[a+1],","===s.type.label&&(s=r[a+2]),this._lastFoundIndex=a;break}}if(s&&"eof"===s.type.label)return 1;var u=this.getNewlinesBetween(e,s);return"CommentLine"!==t.type||u?u:1},t.prototype.getNewlinesBetween=function(t,e){if(!e||!e.loc)return 0;for(var s=t?t.loc.end.line:1,i=e.loc.start.line,r=0,n=s;i>n;n++)"undefined"==typeof this.used[n]&&(this.used[n]=!0,r++);return r},t}();e["default"]=n,t.exports=e["default"]},function(t,e,s){"use strict";function i(t,e){return t.line===e.line&&t.column===e.column}var r=s(21)["default"],n=s(22)["default"],a=s(23)["default"];e.__esModule=!0;var o=s(30),u=n(o),p=s(41),c=a(p),l=function(){function t(e,s,i){r(this,t),this.position=e,this.opts=s,this.last={generated:{},original:{}},s.sourceMaps?(this.map=new u["default"].SourceMapGenerator({file:s.sourceMapTarget,sourceRoot:s.sourceRoot}),this.map.setSourceContent(s.sourceFileName,i)):this.map=null}return t.prototype.get=function(){var t=this.map;return t?t.toJSON():t},t.prototype.mark=function(t){var e=t.loc;if(e){var s=this.map;if(s&&!c.isProgram(t)&&!c.isFile(t)){var r=this.position,n={line:r.line,column:r.column},a=e.start;i(a,this.last.original)||i(n,this.last.generated)||(this.last={source:this.opts.sourceFileName,generated:n,original:a},s.addMapping(this.last))}}},t}();e["default"]=l,t.exports=e["default"]},function(t,e,s){e.SourceMapGenerator=s(31).SourceMapGenerator,e.SourceMapConsumer=s(37).SourceMapConsumer,e.SourceNode=s(40).SourceNode},function(t,e,s){function i(t){t||(t={}),this._file=n.getArg(t,"file",null),this._sourceRoot=n.getArg(t,"sourceRoot",null),this._skipValidation=n.getArg(t,"skipValidation",!1),this._sources=new a,this._names=new a,this._mappings=new o,this._sourcesContents=null}var r=s(32),n=s(34),a=s(35).ArraySet,o=s(36).MappingList;i.prototype._version=3,i.fromSourceMap=function(t){var e=t.sourceRoot,s=new i({file:t.file,sourceRoot:e});return t.eachMapping(function(t){var i={generated:{line:t.generatedLine,column:t.generatedColumn}};null!=t.source&&(i.source=t.source,null!=e&&(i.source=n.relative(e,i.source)),i.original={line:t.originalLine,column:t.originalColumn},null!=t.name&&(i.name=t.name)),s.addMapping(i)}),t.sources.forEach(function(e){var i=t.sourceContentFor(e);null!=i&&s.setSourceContent(e,i)}),s},i.prototype.addMapping=function(t){var e=n.getArg(t,"generated"),s=n.getArg(t,"original",null),i=n.getArg(t,"source",null),r=n.getArg(t,"name",null);this._skipValidation||this._validateMapping(e,s,i,r),null==i||this._sources.has(i)||this._sources.add(i),null==r||this._names.has(r)||this._names.add(r),this._mappings.add({generatedLine:e.line,generatedColumn:e.column,originalLine:null!=s&&s.line,originalColumn:null!=s&&s.column,source:i,name:r})},i.prototype.setSourceContent=function(t,e){var s=t;null!=this._sourceRoot&&(s=n.relative(this._sourceRoot,s)),null!=e?(this._sourcesContents||(this._sourcesContents={}),this._sourcesContents[n.toSetString(s)]=e):this._sourcesContents&&(delete this._sourcesContents[n.toSetString(s)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},i.prototype.applySourceMap=function(t,e,s){var i=e;if(null==e){if(null==t.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');i=t.file}var r=this._sourceRoot;null!=r&&(i=n.relative(r,i));var o=new a,u=new a;this._mappings.unsortedForEach(function(e){if(e.source===i&&null!=e.originalLine){var a=t.originalPositionFor({line:e.originalLine,column:e.originalColumn});null!=a.source&&(e.source=a.source,null!=s&&(e.source=n.join(s,e.source)),null!=r&&(e.source=n.relative(r,e.source)),e.originalLine=a.line,e.originalColumn=a.column,null!=a.name&&(e.name=a.name))}var p=e.source;null==p||o.has(p)||o.add(p);var c=e.name;null==c||u.has(c)||u.add(c)},this),this._sources=o,this._names=u,t.sources.forEach(function(e){var i=t.sourceContentFor(e);null!=i&&(null!=s&&(e=n.join(s,e)),null!=r&&(e=n.relative(r,e)),this.setSourceContent(e,i))},this)},i.prototype._validateMapping=function(t,e,s,i){if((!(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0)||e||s||i)&&!(t&&"line"in t&&"column"in t&&e&&"line"in e&&"column"in e&&t.line>0&&t.column>=0&&e.line>0&&e.column>=0&&s))throw new Error("Invalid mapping: "+JSON.stringify({generated:t,source:s,original:e,name:i}))},i.prototype._serializeMappings=function(){for(var t,e,s,i=0,a=1,o=0,u=0,p=0,c=0,l="",h=this._mappings.toArray(),f=0,d=h.length;d>f;f++){if(t=h[f],t.generatedLine!==a)for(i=0;t.generatedLine!==a;)l+=";",a++;else if(f>0){if(!n.compareByGeneratedPositionsInflated(t,h[f-1]))continue;l+=","}l+=r.encode(t.generatedColumn-i),i=t.generatedColumn,null!=t.source&&(s=this._sources.indexOf(t.source),l+=r.encode(s-c),c=s,l+=r.encode(t.originalLine-1-u),u=t.originalLine-1,l+=r.encode(t.originalColumn-o),o=t.originalColumn,null!=t.name&&(e=this._names.indexOf(t.name),l+=r.encode(e-p),p=e))}return l},i.prototype._generateSourcesContent=function(t,e){return t.map(function(t){if(!this._sourcesContents)return null;null!=e&&(t=n.relative(e,t));var s=n.toSetString(t);return Object.prototype.hasOwnProperty.call(this._sourcesContents,s)?this._sourcesContents[s]:null},this)},i.prototype.toJSON=function(){var t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(t.file=this._file),null!=this._sourceRoot&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot)),t},i.prototype.toString=function(){return JSON.stringify(this.toJSON())},e.SourceMapGenerator=i},function(t,e,s){function i(t){return 0>t?(-t<<1)+1:(t<<1)+0}function r(t){var e=1===(1&t),s=t>>1;return e?-s:s}var n=s(33),a=5,o=1<<a,u=o-1,p=o;e.encode=function(t){var e,s="",r=i(t);do e=r&u,r>>>=a,r>0&&(e|=p),s+=n.encode(e);while(r>0);return s},e.decode=function(t,e,s){var i,o,c=t.length,l=0,h=0;do{if(e>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(o=n.decode(t.charCodeAt(e++)),-1===o)throw new Error("Invalid base64 digit: "+t.charAt(e-1));i=!!(o&p),o&=u,l+=o<<h,h+=a}while(i);s.value=r(l),s.rest=e}},function(t,e){var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");e.encode=function(t){if(t>=0&&t<s.length)return s[t];throw new TypeError("Must be between 0 and 63: "+t)},e.decode=function(t){var e=65,s=90,i=97,r=122,n=48,a=57,o=43,u=47,p=26,c=52;return t>=e&&s>=t?t-e:t>=i&&r>=t?t-i+p:t>=n&&a>=t?t-n+c:t==o?62:t==u?63:-1}},function(t,e){function s(t,e,s){if(e in t)return t[e];if(3===arguments.length)return s;throw new Error('"'+e+'" is a required argument.')}function i(t){var e=t.match(d);return e?{scheme:e[1],auth:e[2],host:e[3],port:e[4],path:e[5]}:null}function r(t){var e="";return t.scheme&&(e+=t.scheme+":"),e+="//",t.auth&&(e+=t.auth+"@"),t.host&&(e+=t.host),t.port&&(e+=":"+t.port),t.path&&(e+=t.path),e}function n(t){var s=t,n=i(t);if(n){if(!n.path)return t;s=n.path}for(var a,o=e.isAbsolute(s),u=s.split(/\/+/),p=0,c=u.length-1;c>=0;c--)a=u[c],"."===a?u.splice(c,1):".."===a?p++:p>0&&(""===a?(u.splice(c+1,p),p=0):(u.splice(c,2),p--));return s=u.join("/"),""===s&&(s=o?"/":"."),n?(n.path=s,r(n)):s}function a(t,e){""===t&&(t="."),""===e&&(e=".");var s=i(e),a=i(t);if(a&&(t=a.path||"/"),s&&!s.scheme)return a&&(s.scheme=a.scheme),r(s);if(s||e.match(y))return e;if(a&&!a.host&&!a.path)return a.host=e,r(a);var o="/"===e.charAt(0)?e:n(t.replace(/\/+$/,"")+"/"+e);return a?(a.path=o,r(a)):o}function o(t,e){""===t&&(t="."),t=t.replace(/\/$/,"");for(var s=0;0!==e.indexOf(t+"/");){var i=t.lastIndexOf("/");if(0>i)return e;if(t=t.slice(0,i),t.match(/^([^\/]+:\/)?\/*$/))return e;++s}return Array(s+1).join("../")+e.substr(t.length+1)}function u(t){return"$"+t}function p(t){return t.substr(1)}function c(t,e,s){var i=t.source-e.source;return 0!==i?i:(i=t.originalLine-e.originalLine,0!==i?i:(i=t.originalColumn-e.originalColumn,0!==i||s?i:(i=t.generatedColumn-e.generatedColumn,0!==i?i:(i=t.generatedLine-e.generatedLine,0!==i?i:t.name-e.name))))}function l(t,e,s){var i=t.generatedLine-e.generatedLine;return 0!==i?i:(i=t.generatedColumn-e.generatedColumn,0!==i||s?i:(i=t.source-e.source,0!==i?i:(i=t.originalLine-e.originalLine,0!==i?i:(i=t.originalColumn-e.originalColumn,0!==i?i:t.name-e.name))))}function h(t,e){return t===e?0:t>e?1:-1}function f(t,e){var s=t.generatedLine-e.generatedLine;return 0!==s?s:(s=t.generatedColumn-e.generatedColumn,0!==s?s:(s=h(t.source,e.source),0!==s?s:(s=t.originalLine-e.originalLine,0!==s?s:(s=t.originalColumn-e.originalColumn,0!==s?s:h(t.name,e.name)))))}e.getArg=s;var d=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,y=/^data:.+\,.+$/;e.urlParse=i,e.urlGenerate=r,e.normalize=n,e.join=a,e.isAbsolute=function(t){return"/"===t.charAt(0)||!!t.match(d)},e.relative=o,e.toSetString=u,e.fromSetString=p,e.compareByOriginalPositions=c,e.compareByGeneratedPositionsDeflated=l,e.compareByGeneratedPositionsInflated=f},function(t,e,s){function i(){this._array=[],this._set={}}var r=s(34);i.fromArray=function(t,e){for(var s=new i,r=0,n=t.length;n>r;r++)s.add(t[r],e);return s},i.prototype.size=function(){return Object.getOwnPropertyNames(this._set).length},i.prototype.add=function(t,e){var s=r.toSetString(t),i=this._set.hasOwnProperty(s),n=this._array.length;(!i||e)&&this._array.push(t),i||(this._set[s]=n)},i.prototype.has=function(t){var e=r.toSetString(t);return this._set.hasOwnProperty(e)},i.prototype.indexOf=function(t){var e=r.toSetString(t);if(this._set.hasOwnProperty(e))return this._set[e];throw new Error('"'+t+'" is not in the set.')},i.prototype.at=function(t){if(t>=0&&t<this._array.length)return this._array[t];throw new Error("No element indexed by "+t)},i.prototype.toArray=function(){return this._array.slice()},e.ArraySet=i},function(t,e,s){function i(t,e){var s=t.generatedLine,i=e.generatedLine,r=t.generatedColumn,a=e.generatedColumn;return i>s||i==s&&a>=r||n.compareByGeneratedPositionsInflated(t,e)<=0}function r(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var n=s(34);r.prototype.unsortedForEach=function(t,e){this._array.forEach(t,e)},r.prototype.add=function(t){i(this._last,t)?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t))},r.prototype.toArray=function(){return this._sorted||(this._array.sort(n.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},e.MappingList=r},function(t,e,s){function i(t){var e=t;return"string"==typeof t&&(e=JSON.parse(t.replace(/^\)\]\}'/,""))),null!=e.sections?new a(e):new r(e)}function r(t){var e=t;"string"==typeof t&&(e=JSON.parse(t.replace(/^\)\]\}'/,"")));var s=o.getArg(e,"version"),i=o.getArg(e,"sources"),r=o.getArg(e,"names",[]),n=o.getArg(e,"sourceRoot",null),a=o.getArg(e,"sourcesContent",null),u=o.getArg(e,"mappings"),c=o.getArg(e,"file",null);if(s!=this._version)throw new Error("Unsupported version: "+s);i=i.map(o.normalize).map(function(t){return n&&o.isAbsolute(n)&&o.isAbsolute(t)?o.relative(n,t):t}),this._names=p.fromArray(r,!0),this._sources=p.fromArray(i,!0),this.sourceRoot=n,this.sourcesContent=a,this._mappings=u,this.file=c}function n(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function a(t){var e=t;"string"==typeof t&&(e=JSON.parse(t.replace(/^\)\]\}'/,"")));var s=o.getArg(e,"version"),r=o.getArg(e,"sections");if(s!=this._version)throw new Error("Unsupported version: "+s);this._sources=new p,this._names=new p;var n={line:-1,column:0};this._sections=r.map(function(t){if(t.url)throw new Error("Support for url field in sections not implemented.");var e=o.getArg(t,"offset"),s=o.getArg(e,"line"),r=o.getArg(e,"column");if(s<n.line||s===n.line&&r<n.column)throw new Error("Section offsets must be ordered and non-overlapping.");return n=e,{generatedOffset:{generatedLine:s+1,generatedColumn:r+1},consumer:new i(o.getArg(t,"map"))}})}var o=s(34),u=s(38),p=s(35).ArraySet,c=s(32),l=s(39).quickSort;i.fromSourceMap=function(t){return r.fromSourceMap(t)},i.prototype._version=3,i.prototype.__generatedMappings=null,Object.defineProperty(i.prototype,"_generatedMappings",{get:function(){return this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappings}}),i.prototype.__originalMappings=null,Object.defineProperty(i.prototype,"_originalMappings",{get:function(){return this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappings}}),i.prototype._charIsMappingSeparator=function(t,e){var s=t.charAt(e);return";"===s||","===s},i.prototype._parseMappings=function(t,e){throw new Error("Subclasses must implement _parseMappings")},i.GENERATED_ORDER=1,i.ORIGINAL_ORDER=2,i.GREATEST_LOWER_BOUND=1,i.LEAST_UPPER_BOUND=2,i.prototype.eachMapping=function(t,e,s){var r,n=e||null,a=s||i.GENERATED_ORDER;switch(a){case i.GENERATED_ORDER:r=this._generatedMappings;break;case i.ORIGINAL_ORDER:r=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var u=this.sourceRoot;r.map(function(t){var e=null===t.source?null:this._sources.at(t.source);return null!=e&&null!=u&&(e=o.join(u,e)),{source:e,generatedLine:t.generatedLine,generatedColumn:t.generatedColumn,originalLine:t.originalLine,originalColumn:t.originalColumn,name:null===t.name?null:this._names.at(t.name)}},this).forEach(t,n)},i.prototype.allGeneratedPositionsFor=function(t){var e=o.getArg(t,"line"),s={source:o.getArg(t,"source"),originalLine:e,originalColumn:o.getArg(t,"column",0)};if(null!=this.sourceRoot&&(s.source=o.relative(this.sourceRoot,s.source)),!this._sources.has(s.source))return[];s.source=this._sources.indexOf(s.source);var i=[],r=this._findMapping(s,this._originalMappings,"originalLine","originalColumn",o.compareByOriginalPositions,u.LEAST_UPPER_BOUND);if(r>=0){var n=this._originalMappings[r];if(void 0===t.column)for(var a=n.originalLine;n&&n.originalLine===a;)i.push({line:o.getArg(n,"generatedLine",null),column:o.getArg(n,"generatedColumn",null),lastColumn:o.getArg(n,"lastGeneratedColumn",null)}),n=this._originalMappings[++r];else for(var p=n.originalColumn;n&&n.originalLine===e&&n.originalColumn==p;)i.push({line:o.getArg(n,"generatedLine",null),column:o.getArg(n,"generatedColumn",null),lastColumn:o.getArg(n,"lastGeneratedColumn",null)}),n=this._originalMappings[++r]}return i},e.SourceMapConsumer=i,r.prototype=Object.create(i.prototype),r.prototype.consumer=i,r.fromSourceMap=function(t){var e=Object.create(r.prototype),s=e._names=p.fromArray(t._names.toArray(),!0),i=e._sources=p.fromArray(t._sources.toArray(),!0);e.sourceRoot=t._sourceRoot,e.sourcesContent=t._generateSourcesContent(e._sources.toArray(),e.sourceRoot),e.file=t._file;for(var a=t._mappings.toArray().slice(),u=e.__generatedMappings=[],c=e.__originalMappings=[],h=0,f=a.length;f>h;h++){var d=a[h],y=new n;y.generatedLine=d.generatedLine,y.generatedColumn=d.generatedColumn,d.source&&(y.source=i.indexOf(d.source),y.originalLine=d.originalLine,y.originalColumn=d.originalColumn,d.name&&(y.name=s.indexOf(d.name)),c.push(y)),u.push(y)}return l(e.__originalMappings,o.compareByOriginalPositions),e},r.prototype._version=3,Object.defineProperty(r.prototype,"sources",{get:function(){return this._sources.toArray().map(function(t){return null!=this.sourceRoot?o.join(this.sourceRoot,t):t},this)}}),r.prototype._parseMappings=function(t,e){for(var s,i,r,a,u,p=1,h=0,f=0,d=0,y=0,m=0,v=t.length,g=0,x={},A={},b=[],E=[];v>g;)if(";"===t.charAt(g))p++,g++,h=0;else if(","===t.charAt(g))g++;else{for(s=new n,s.generatedLine=p,a=g;v>a&&!this._charIsMappingSeparator(t,a);a++);if(i=t.slice(g,a),r=x[i])g+=i.length;else{for(r=[];a>g;)c.decode(t,g,A),u=A.value,g=A.rest,r.push(u);if(2===r.length)throw new Error("Found a source, but no line and column");if(3===r.length)throw new Error("Found a source and line, but no column");x[i]=r}s.generatedColumn=h+r[0],h=s.generatedColumn,r.length>1&&(s.source=y+r[1],y+=r[1],s.originalLine=f+r[2],f=s.originalLine,s.originalLine+=1,s.originalColumn=d+r[3],d=s.originalColumn,r.length>4&&(s.name=m+r[4],m+=r[4])),E.push(s),"number"==typeof s.originalLine&&b.push(s)}l(E,o.compareByGeneratedPositionsDeflated),this.__generatedMappings=E,l(b,o.compareByOriginalPositions),this.__originalMappings=b},r.prototype._findMapping=function(t,e,s,i,r,n){if(t[s]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+t[s]);if(t[i]<0)throw new TypeError("Column must be greater than or equal to 0, got "+t[i]);return u.search(t,e,r,n)},r.prototype.computeColumnSpans=function(){for(var t=0;t<this._generatedMappings.length;++t){var e=this._generatedMappings[t];if(t+1<this._generatedMappings.length){var s=this._generatedMappings[t+1];if(e.generatedLine===s.generatedLine){e.lastGeneratedColumn=s.generatedColumn-1;continue}}e.lastGeneratedColumn=1/0}},r.prototype.originalPositionFor=function(t){var e={generatedLine:o.getArg(t,"line"),generatedColumn:o.getArg(t,"column")},s=this._findMapping(e,this._generatedMappings,"generatedLine","generatedColumn",o.compareByGeneratedPositionsDeflated,o.getArg(t,"bias",i.GREATEST_LOWER_BOUND));if(s>=0){var r=this._generatedMappings[s];if(r.generatedLine===e.generatedLine){var n=o.getArg(r,"source",null);null!==n&&(n=this._sources.at(n),null!=this.sourceRoot&&(n=o.join(this.sourceRoot,n)));var a=o.getArg(r,"name",null);return null!==a&&(a=this._names.at(a)),{source:n,line:o.getArg(r,"originalLine",null),column:o.getArg(r,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}},r.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(t){return null==t}):!1},r.prototype.sourceContentFor=function(t,e){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(t=o.relative(this.sourceRoot,t)),this._sources.has(t))return this.sourcesContent[this._sources.indexOf(t)];var s;if(null!=this.sourceRoot&&(s=o.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==s.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!s.path||"/"==s.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(e)return null;throw new Error('"'+t+'" is not in the SourceMap.')},r.prototype.generatedPositionFor=function(t){ var e=o.getArg(t,"source");if(null!=this.sourceRoot&&(e=o.relative(this.sourceRoot,e)),!this._sources.has(e))return{line:null,column:null,lastColumn:null};e=this._sources.indexOf(e);var s={source:e,originalLine:o.getArg(t,"line"),originalColumn:o.getArg(t,"column")},r=this._findMapping(s,this._originalMappings,"originalLine","originalColumn",o.compareByOriginalPositions,o.getArg(t,"bias",i.GREATEST_LOWER_BOUND));if(r>=0){var n=this._originalMappings[r];if(n.source===s.source)return{line:o.getArg(n,"generatedLine",null),column:o.getArg(n,"generatedColumn",null),lastColumn:o.getArg(n,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},e.BasicSourceMapConsumer=r,a.prototype=Object.create(i.prototype),a.prototype.constructor=i,a.prototype._version=3,Object.defineProperty(a.prototype,"sources",{get:function(){for(var t=[],e=0;e<this._sections.length;e++)for(var s=0;s<this._sections[e].consumer.sources.length;s++)t.push(this._sections[e].consumer.sources[s]);return t}}),a.prototype.originalPositionFor=function(t){var e={generatedLine:o.getArg(t,"line"),generatedColumn:o.getArg(t,"column")},s=u.search(e,this._sections,function(t,e){var s=t.generatedLine-e.generatedOffset.generatedLine;return s?s:t.generatedColumn-e.generatedOffset.generatedColumn}),i=this._sections[s];return i?i.consumer.originalPositionFor({line:e.generatedLine-(i.generatedOffset.generatedLine-1),column:e.generatedColumn-(i.generatedOffset.generatedLine===e.generatedLine?i.generatedOffset.generatedColumn-1:0),bias:t.bias}):{source:null,line:null,column:null,name:null}},a.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(t){return t.consumer.hasContentsOfAllSources()})},a.prototype.sourceContentFor=function(t,e){for(var s=0;s<this._sections.length;s++){var i=this._sections[s],r=i.consumer.sourceContentFor(t,!0);if(r)return r}if(e)return null;throw new Error('"'+t+'" is not in the SourceMap.')},a.prototype.generatedPositionFor=function(t){for(var e=0;e<this._sections.length;e++){var s=this._sections[e];if(-1!==s.consumer.sources.indexOf(o.getArg(t,"source"))){var i=s.consumer.generatedPositionFor(t);if(i){var r={line:i.line+(s.generatedOffset.generatedLine-1),column:i.column+(s.generatedOffset.generatedLine===i.line?s.generatedOffset.generatedColumn-1:0)};return r}}}return{line:null,column:null}},a.prototype._parseMappings=function(t,e){this.__generatedMappings=[],this.__originalMappings=[];for(var s=0;s<this._sections.length;s++)for(var i=this._sections[s],r=i.consumer._generatedMappings,n=0;n<r.length;n++){var a=r[n],u=i.consumer._sources.at(a.source);null!==i.consumer.sourceRoot&&(u=o.join(i.consumer.sourceRoot,u)),this._sources.add(u),u=this._sources.indexOf(u);var p=i.consumer._names.at(a.name);this._names.add(p),p=this._names.indexOf(p);var c={source:u,generatedLine:a.generatedLine+(i.generatedOffset.generatedLine-1),generatedColumn:a.generatedColumn+(i.generatedOffset.generatedLine===a.generatedLine?i.generatedOffset.generatedColumn-1:0),originalLine:a.originalLine,originalColumn:a.originalColumn,name:p};this.__generatedMappings.push(c),"number"==typeof c.originalLine&&this.__originalMappings.push(c)}l(this.__generatedMappings,o.compareByGeneratedPositionsDeflated),l(this.__originalMappings,o.compareByOriginalPositions)},e.IndexedSourceMapConsumer=a},function(t,e){function s(t,i,r,n,a,o){var u=Math.floor((i-t)/2)+t,p=a(r,n[u],!0);return 0===p?u:p>0?i-u>1?s(u,i,r,n,a,o):o==e.LEAST_UPPER_BOUND?i<n.length?i:-1:u:u-t>1?s(t,u,r,n,a,o):o==e.LEAST_UPPER_BOUND?u:0>t?-1:t}e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=2,e.search=function(t,i,r,n){if(0===i.length)return-1;var a=s(-1,i.length,t,i,r,n||e.GREATEST_LOWER_BOUND);if(0>a)return-1;for(;a-1>=0&&0===r(i[a],i[a-1],!0);)--a;return a}},function(t,e){function s(t,e,s){var i=t[e];t[e]=t[s],t[s]=i}function i(t,e){return Math.round(t+Math.random()*(e-t))}function r(t,e,n,a){if(a>n){var o=i(n,a),u=n-1;s(t,o,a);for(var p=t[a],c=n;a>c;c++)e(t[c],p)<=0&&(u+=1,s(t,u,c));s(t,u+1,c);var l=u+1;r(t,e,n,l-1),r(t,e,l+1,a)}}e.quickSort=function(t,e){r(t,e,0,t.length-1)}},function(t,e,s){function i(t,e,s,i,r){this.children=[],this.sourceContents={},this.line=null==t?null:t,this.column=null==e?null:e,this.source=null==s?null:s,this.name=null==r?null:r,this[u]=!0,null!=i&&this.add(i)}var r=s(31).SourceMapGenerator,n=s(34),a=/(\r?\n)/,o=10,u="$$$isSourceNode$$$";i.fromStringWithSourceMap=function(t,e,s){function r(t,e){if(null===t||void 0===t.source)o.add(e);else{var r=s?n.join(s,t.source):t.source;o.add(new i(t.originalLine,t.originalColumn,r,e,t.name))}}var o=new i,u=t.split(a),p=function(){var t=u.shift(),e=u.shift()||"";return t+e},c=1,l=0,h=null;return e.eachMapping(function(t){if(null!==h){if(!(c<t.generatedLine)){var e=u[0],s=e.substr(0,t.generatedColumn-l);return u[0]=e.substr(t.generatedColumn-l),l=t.generatedColumn,r(h,s),void(h=t)}r(h,p()),c++,l=0}for(;c<t.generatedLine;)o.add(p()),c++;if(l<t.generatedColumn){var e=u[0];o.add(e.substr(0,t.generatedColumn)),u[0]=e.substr(t.generatedColumn),l=t.generatedColumn}h=t},this),u.length>0&&(h&&r(h,p()),o.add(u.join(""))),e.sources.forEach(function(t){var i=e.sourceContentFor(t);null!=i&&(null!=s&&(t=n.join(s,t)),o.setSourceContent(t,i))}),o},i.prototype.add=function(t){if(Array.isArray(t))t.forEach(function(t){this.add(t)},this);else{if(!t[u]&&"string"!=typeof t)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+t);t&&this.children.push(t)}return this},i.prototype.prepend=function(t){if(Array.isArray(t))for(var e=t.length-1;e>=0;e--)this.prepend(t[e]);else{if(!t[u]&&"string"!=typeof t)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+t);this.children.unshift(t)}return this},i.prototype.walk=function(t){for(var e,s=0,i=this.children.length;i>s;s++)e=this.children[s],e[u]?e.walk(t):""!==e&&t(e,{source:this.source,line:this.line,column:this.column,name:this.name})},i.prototype.join=function(t){var e,s,i=this.children.length;if(i>0){for(e=[],s=0;i-1>s;s++)e.push(this.children[s]),e.push(t);e.push(this.children[s]),this.children=e}return this},i.prototype.replaceRight=function(t,e){var s=this.children[this.children.length-1];return s[u]?s.replaceRight(t,e):"string"==typeof s?this.children[this.children.length-1]=s.replace(t,e):this.children.push("".replace(t,e)),this},i.prototype.setSourceContent=function(t,e){this.sourceContents[n.toSetString(t)]=e},i.prototype.walkSourceContents=function(t){for(var e=0,s=this.children.length;s>e;e++)this.children[e][u]&&this.children[e].walkSourceContents(t);for(var i=Object.keys(this.sourceContents),e=0,s=i.length;s>e;e++)t(n.fromSetString(i[e]),this.sourceContents[i[e]])},i.prototype.toString=function(){var t="";return this.walk(function(e){t+=e}),t},i.prototype.toStringWithSourceMap=function(t){var e={code:"",line:1,column:0},s=new r(t),i=!1,n=null,a=null,u=null,p=null;return this.walk(function(t,r){e.code+=t,null!==r.source&&null!==r.line&&null!==r.column?((n!==r.source||a!==r.line||u!==r.column||p!==r.name)&&s.addMapping({source:r.source,original:{line:r.line,column:r.column},generated:{line:e.line,column:e.column},name:r.name}),n=r.source,a=r.line,u=r.column,p=r.name,i=!0):i&&(s.addMapping({generated:{line:e.line,column:e.column}}),n=null,i=!1);for(var c=0,l=t.length;l>c;c++)t.charCodeAt(c)===o?(e.line++,e.column=0,c+1===l?(n=null,i=!1):i&&s.addMapping({source:r.source,original:{line:r.line,column:r.column},generated:{line:e.line,column:e.column},name:r.name})):e.column++}),this.walkSourceContents(function(t,e){s.setSourceContent(t,e)}),{code:e.code,map:s}},e.SourceNode=i},function(t,e,s){"use strict";function i(t){var e=q["is"+t]=function(e,s){return q.is(t,e,s)};q["assert"+t]=function(s,i){if(i=i||{},!e(s,i))throw new Error("Expected type "+JSON.stringify(t)+" with option "+JSON.stringify(i))}}function r(t,e,s){if(!e)return!1;var i=n(e.type,t);return i?"undefined"==typeof s?!0:q.shallowEqual(e,s):!1}function n(t,e){if(t===e)return!0;var s=q.FLIPPED_ALIAS_KEYS[e];if(s){if(s[0]===t)return!0;for(var i=s,r=Array.isArray(i),n=0,i=r?i:S(i);;){var a;if(r){if(n>=i.length)break;a=i[n++]}else{if(n=i.next(),n.done)break;a=n.value}var o=a;if(t===o)return!0}}return!1}function a(t,e,s){if(t){var i=q.NODE_FIELDS[t.type];if(i){var r=i[e];r&&r.validate&&(r.optional&&null==s||r.validate(t,e,s))}}}function o(t,e){for(var s=D(e),i=s,r=Array.isArray(i),n=0,i=r?i:S(i);;){var a;if(r){if(n>=i.length)break;a=i[n++]}else{if(n=i.next(),n.done)break;a=n.value}var o=a;if(t[o]!==e[o])return!1}return!0}function u(t,e,s){return t.object=q.memberExpression(t.object,t.property,t.computed),t.property=e,t.computed=!!s,t}function p(t,e){return t.object=q.memberExpression(e,t.object),t}function c(t){var e=arguments.length<=1||void 0===arguments[1]?"body":arguments[1];return t[e]=q.toBlock(t[e],t)}function l(t){var e={};for(var s in t)"_"!==s[0]&&(e[s]=t[s]);return e}function h(t){var e=l(t);return delete e.loc,e}function f(t){var e={};for(var s in t)if("_"!==s[0]){var i=t[s];i&&(i.type?i=q.cloneDeep(i):Array.isArray(i)&&(i=i.map(q.cloneDeep))),e[s]=i}return e}function d(t,e){var s=t.split(".");return function(t){if(!q.isMemberExpression(t))return!1;for(var i=[t],r=0;i.length;){var n=i.shift();if(e&&r===s.length)return!0;if(q.isIdentifier(n)){if(s[r]!==n.name)return!1}else{if(!q.isStringLiteral(n)){if(q.isMemberExpression(n)){if(n.computed&&!q.isStringLiteral(n.property))return!1;i.push(n.object),i.push(n.property);continue}return!1}if(s[r]!==n.value)return!1}if(++r>s.length)return!1}return!0}}function y(t){for(var e=q.COMMENT_KEYS,s=Array.isArray(e),i=0,e=s?e:S(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var n=r;delete t[n]}return t}function m(t,e){return v(t,e),g(t,e),x(t,e),t}function v(t,e){A("trailingComments",t,e)}function g(t,e){A("leadingComments",t,e)}function x(t,e){A("innerComments",t,e)}function A(t,e,s){e&&s&&(e[t]=R["default"](N["default"]([].concat(e[t],s[t]))))}function b(t,e){if(!t||!e)return t;for(var s=q.INHERIT_KEYS.optional,i=Array.isArray(s),r=0,s=i?s:S(s);;){var n;if(i){if(r>=s.length)break;n=s[r++]}else{if(r=s.next(),r.done)break;n=r.value}var a=n;null==t[a]&&(t[a]=e[a])}for(var a in e)"_"===a[0]&&(t[a]=e[a]);for(var o=q.INHERIT_KEYS.force,u=Array.isArray(o),p=0,o=u?o:S(o);;){var c;if(u){if(p>=o.length)break;c=o[p++]}else{if(p=o.next(),p.done)break;c=p.value}var a=c;t[a]=e[a]}return q.inheritsComments(t,e),t}function E(t){if(!C(t))throw new TypeError("Not a valid node "+(t&&t.type))}function C(t){return!(!t||!V.VISITOR_KEYS[t.type])}var D=s(42)["default"],S=s(54)["default"],F=s(85)["default"],w=s(86)["default"],T=s(87)["default"],k=s(97)["default"];e.__esModule=!0,e.is=r,e.isType=n,e.validate=a,e.shallowEqual=o,e.appendToMemberExpression=u,e.prependToMemberExpression=p,e.ensureBlock=c,e.clone=l,e.cloneWithoutLoc=h,e.cloneDeep=f,e.buildMatchMemberExpression=d,e.removeComments=y,e.inheritsComments=m,e.inheritTrailingComments=v,e.inheritLeadingComments=g,e.inheritInnerComments=x,e.inherits=b,e.assertNode=E,e.isNode=C;var P=s(98),_=F(P),B=s(99),N=F(B),L=s(100),I=F(L),O=s(132),M=F(O),j=s(137),R=F(j);s(168);var V=s(169),$=s(183),G=w($),q=e,U=s(171);T(e,k(U,T)),e.VISITOR_KEYS=V.VISITOR_KEYS,e.ALIAS_KEYS=V.ALIAS_KEYS,e.NODE_FIELDS=V.NODE_FIELDS,e.BUILDER_KEYS=V.BUILDER_KEYS,e.DEPRECATED_KEYS=V.DEPRECATED_KEYS,e.react=G;for(var W in q.VISITOR_KEYS)i(W);q.FLIPPED_ALIAS_KEYS={},M["default"](q.ALIAS_KEYS,function(t,e){M["default"](t,function(t){var s=q.FLIPPED_ALIAS_KEYS[t]=q.FLIPPED_ALIAS_KEYS[t]||[];s.push(e)})}),M["default"](q.FLIPPED_ALIAS_KEYS,function(t,e){q[e.toUpperCase()+"_TYPES"]=t,i(e)});var X=D(q.VISITOR_KEYS).concat(D(q.FLIPPED_ALIAS_KEYS)).concat(D(q.DEPRECATED_KEYS));e.TYPES=X,M["default"](q.BUILDER_KEYS,function(t,e){function s(){if(arguments.length>t.length)throw new Error("t."+e+": Too many arguments passed. Received "+arguments.length+" but can receive no more than "+t.length);var s={};s.type=e;for(var i=0,r=t,n=Array.isArray(r),o=0,r=n?r:S(r);;){var u;if(n){if(o>=r.length)break;u=r[o++]}else{if(o=r.next(),o.done)break;u=o.value}var p=u,c=q.NODE_FIELDS[e][p],l=arguments[i++];void 0===l&&(l=I["default"](c["default"])),s[p]=l}for(var p in s)a(s,p,s[p]);return s}q[e]=s,q[e[0].toLowerCase()+e.slice(1)]=s});var J=function(t){var e=function(e){return function(){return console.trace("The node type "+t+" has been renamed to "+s),e.apply(this,arguments)}},s=q.DEPRECATED_KEYS[t];q[t]=q[t[0].toLowerCase()+t.slice(1)]=e(q[s]),q["is"+t]=e(q["is"+s]),q["assert"+t]=e(q["assert"+s])};for(var W in q.DEPRECATED_KEYS)J(W);_["default"](q),_["default"](q.VISITOR_KEYS);var K=s(184);T(e,k(K,T));var H=s(187);T(e,k(H,T));var z=s(192);T(e,k(z,T));var Y=s(271);T(e,k(Y,T))},function(t,e,s){t.exports={"default":s(43),__esModule:!0}},function(t,e,s){s(44),t.exports=s(50).Object.keys},function(t,e,s){var i=s(45);s(47)("keys",function(t){return function(e){return t(i(e))}})},function(t,e,s){var i=s(46);t.exports=function(t){return Object(i(t))}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,s){var i=s(48),r=s(50),n=s(53);t.exports=function(t,e){var s=(r.Object||{})[t]||Object[t],a={};a[t]=e(s),i(i.S+i.F*n(function(){s(1)}),"Object",a)}},function(t,e,s){var i=s(49),r=s(50),n=s(51),a="prototype",o=function(t,e,s){var u,p,c,l=t&o.F,h=t&o.G,f=t&o.S,d=t&o.P,y=t&o.B,m=t&o.W,v=h?r:r[e]||(r[e]={}),g=h?i:f?i[e]:(i[e]||{})[a];h&&(s=e);for(u in s)p=!l&&g&&u in g,p&&u in v||(c=p?g[u]:s[u],v[u]=h&&"function"!=typeof g[u]?s[u]:y&&p?n(c,i):m&&g[u]==c?function(t){var e=function(e){return this instanceof t?new t(e):t(e)};return e[a]=t[a],e}(c):d&&"function"==typeof c?n(Function.call,c):c,d&&((v[a]||(v[a]={}))[u]=c))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,t.exports=o},function(t,e){var s=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=s)},function(t,e){var s=t.exports={version:"1.2.6"};"number"==typeof __e&&(__e=s)},function(t,e,s){var i=s(52);t.exports=function(t,e,s){if(i(t),void 0===e)return t;switch(s){case 1:return function(s){return t.call(e,s)};case 2:return function(s,i){return t.call(e,s,i)};case 3:return function(s,i,r){return t.call(e,s,i,r)}}return function(){return t.apply(e,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e){t.exports=function(t){try{return!!t()}catch(e){return!0}}},function(t,e,s){t.exports={"default":s(55),__esModule:!0}},function(t,e,s){s(56),s(77),t.exports=s(80)},function(t,e,s){s(57);var i=s(60);i.NodeList=i.HTMLCollection=i.Array},function(t,e,s){"use strict";var i=s(58),r=s(59),n=s(60),a=s(61);t.exports=s(64)(Array,"Array",function(t,e){this._t=a(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,s=this._i++;return!t||s>=t.length?(this._t=void 0,r(1)):"keys"==e?r(0,s):"values"==e?r(0,t[s]):r(0,[s,t[s]])},"values"),n.Arguments=n.Array,i("keys"),i("values"),i("entries")},function(t,e){t.exports=function(){}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e){t.exports={}},function(t,e,s){var i=s(62),r=s(46);t.exports=function(t){return i(r(t))}},function(t,e,s){var i=s(63);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==i(t)?t.split(""):Object(t)}},function(t,e){var s={}.toString;t.exports=function(t){return s.call(t).slice(8,-1)}},function(t,e,s){"use strict";var i=s(65),r=s(48),n=s(66),a=s(67),o=s(71),u=s(60),p=s(72),c=s(73),l=s(68).getProto,h=s(74)("iterator"),f=!([].keys&&"next"in[].keys()),d="@@iterator",y="keys",m="values",v=function(){return this};t.exports=function(t,e,s,g,x,A,b){p(s,e,g);var E,C,D=function(t){if(!f&&t in T)return T[t];switch(t){case y:return function(){return new s(this,t)};case m:return function(){return new s(this,t)}}return function(){return new s(this,t)}},S=e+" Iterator",F=x==m,w=!1,T=t.prototype,k=T[h]||T[d]||x&&T[x],P=k||D(x);if(k){var _=l(P.call(new t));c(_,S,!0),!i&&o(T,d)&&a(_,h,v),F&&k.name!==m&&(w=!0,P=function(){return k.call(this)})}if(i&&!b||!f&&!w&&T[h]||a(T,h,P),u[e]=P,u[S]=v,x)if(E={values:F?P:D(m),keys:A?P:D(y),entries:F?D("entries"):P},b)for(C in E)C in T||n(T,C,E[C]);else r(r.P+r.F*(f||w),e,E);return E}},function(t,e){t.exports=!0},function(t,e,s){t.exports=s(67)},function(t,e,s){var i=s(68),r=s(69);t.exports=s(70)?function(t,e,s){return i.setDesc(t,e,r(1,s))}:function(t,e,s){return t[e]=s,t}},function(t,e){var s=Object;t.exports={create:s.create,getProto:s.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:s.getOwnPropertyDescriptor,setDesc:s.defineProperty,setDescs:s.defineProperties,getKeys:s.keys,getNames:s.getOwnPropertyNames,getSymbols:s.getOwnPropertySymbols,each:[].forEach}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,s){t.exports=!s(53)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){var s={}.hasOwnProperty;t.exports=function(t,e){return s.call(t,e)}},function(t,e,s){"use strict";var i=s(68),r=s(69),n=s(73),a={};s(67)(a,s(74)("iterator"),function(){return this}),t.exports=function(t,e,s){t.prototype=i.create(a,{next:r(1,s)}),n(t,e+" Iterator")}},function(t,e,s){var i=s(68).setDesc,r=s(71),n=s(74)("toStringTag");t.exports=function(t,e,s){t&&!r(t=s?t:t.prototype,n)&&i(t,n,{configurable:!0,value:e})}},function(t,e,s){var i=s(75)("wks"),r=s(76),n=s(49).Symbol;t.exports=function(t){return i[t]||(i[t]=n&&n[t]||(n||r)("Symbol."+t))}},function(t,e,s){var i=s(49),r="__core-js_shared__",n=i[r]||(i[r]={});t.exports=function(t){return n[t]||(n[t]={})}},function(t,e){var s=0,i=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++s+i).toString(36))}},function(t,e,s){"use strict";var i=s(78)(!0);s(64)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,s=this._i;return s>=e.length?{value:void 0,done:!0}:(t=i(e,s),this._i+=t.length,{value:t,done:!1})})},function(t,e,s){var i=s(79),r=s(46);t.exports=function(t){return function(e,s){var n,a,o=String(r(e)),u=i(s),p=o.length;return 0>u||u>=p?t?"":void 0:(n=o.charCodeAt(u),55296>n||n>56319||u+1===p||(a=o.charCodeAt(u+1))<56320||a>57343?t?o.charAt(u):n:t?o.slice(u,u+2):(n-55296<<10)+(a-56320)+65536)}}},function(t,e){var s=Math.ceil,i=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?i:s)(t)}},function(t,e,s){var i=s(81),r=s(83);t.exports=s(50).getIterator=function(t){var e=r(t);if("function"!=typeof e)throw TypeError(t+" is not iterable!");return i(e.call(t))}},function(t,e,s){var i=s(82);t.exports=function(t){if(!i(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,s){var i=s(84),r=s(74)("iterator"),n=s(60);t.exports=s(50).getIteratorMethod=function(t){return void 0!=t?t[r]||t["@@iterator"]||n[i(t)]:void 0}},function(t,e,s){var i=s(63),r=s(74)("toStringTag"),n="Arguments"==i(function(){return arguments}());t.exports=function(t){var e,s,a;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(s=(e=Object(t))[r])?s:n?i(e):"Object"==(a=i(e))&&"function"==typeof e.callee?"Arguments":a}},function(t,e){"use strict";e["default"]=function(t){return t&&t.__esModule?t:{"default":t}},e.__esModule=!0},function(t,e){"use strict";e["default"]=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e["default"]=t,e},e.__esModule=!0},function(t,e,s){"use strict";var i=s(88)["default"],r=s(92)["default"],n=s(95)["default"];e["default"]=function(t,e){for(var s=i(e),a=0;a<s.length;a++){var o=s[a],u=r(e,o);u&&u.configurable&&void 0===t[o]&&n(t,o,u)}return t},e.__esModule=!0},function(t,e,s){t.exports={"default":s(89),__esModule:!0}},function(t,e,s){var i=s(68);s(90),t.exports=function(t){return i.getNames(t)}},function(t,e,s){s(47)("getOwnPropertyNames",function(){return s(91).get})},function(t,e,s){var i=s(61),r=s(68).getNames,n={}.toString,a="object"==typeof window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],o=function(t){try{return r(t)}catch(e){return a.slice()}};t.exports.get=function(t){return a&&"[object Window]"==n.call(t)?o(t):r(i(t))}},function(t,e,s){t.exports={"default":s(93),__esModule:!0}},function(t,e,s){var i=s(68);s(94),t.exports=function(t,e){return i.getDesc(t,e)}},function(t,e,s){var i=s(61);s(47)("getOwnPropertyDescriptor",function(t){return function(e,s){return t(i(e),s)}})},function(t,e,s){t.exports={"default":s(96),__esModule:!0}},function(t,e,s){var i=s(68);t.exports=function(t,e,s){return i.setDesc(t,e,s)}},function(t,e){"use strict";e["default"]=function(t,e){var s=e({},t);return delete s["default"],s},e.__esModule=!0},function(t,e){"use strict";t.exports=function s(t){function e(){}e.prototype=t,new e}},function(t,e){function s(t){for(var e=-1,s=t?t.length:0,i=-1,r=[];++e<s;){var n=t[e];n&&(r[++i]=n)}return r}t.exports=s},function(t,e,s){function i(t,e,s,i){return e&&"boolean"!=typeof e&&a(t,e,s)?e=!1:"function"==typeof e&&(i=s,s=e,e=!1),"function"==typeof s?r(t,e,n(s,i,3)):r(t,e)}var r=s(101),n=s(129),a=s(131);t.exports=i},function(t,e,s){function i(t,e,s,d,y,m,v){var x;if(s&&(x=y?s(t,d,y):s(t)),void 0!==x)return x;if(!h(t))return t;var A=l(t);if(A){if(x=u(t),!e)return r(t,x)}else{var E=j.call(t),C=E==g;if(E!=b&&E!=f&&(!C||y))return O[E]?p(t,E,e):y?t:{};if(x=c(C?{}:t),!e)return a(x,t)}m||(m=[]),v||(v=[]);for(var D=m.length;D--;)if(m[D]==t)return v[D];return m.push(t),v.push(x),(A?n:o)(t,function(r,n){x[n]=i(r,e,s,n,t,m,v)}),x}var r=s(102),n=s(103),a=s(104),o=s(121),u=s(125),p=s(126),c=s(128),l=s(118),h=s(110),f="[object Arguments]",d="[object Array]",y="[object Boolean]",m="[object Date]",v="[object Error]",g="[object Function]",x="[object Map]",A="[object Number]",b="[object Object]",E="[object RegExp]",C="[object Set]",D="[object String]",S="[object WeakMap]",F="[object ArrayBuffer]",w="[object Float32Array]",T="[object Float64Array]",k="[object Int8Array]",P="[object Int16Array]",_="[object Int32Array]",B="[object Uint8Array]",N="[object Uint8ClampedArray]",L="[object Uint16Array]",I="[object Uint32Array]",O={};O[f]=O[d]=O[F]=O[y]=O[m]=O[w]=O[T]=O[k]=O[P]=O[_]=O[A]=O[b]=O[E]=O[D]=O[B]=O[N]=O[L]=O[I]=!0,O[v]=O[g]=O[x]=O[C]=O[S]=!1;var M=Object.prototype,j=M.toString;t.exports=i},function(t,e){function s(t,e){var s=-1,i=t.length;for(e||(e=Array(i));++s<i;)e[s]=t[s];return e}t.exports=s},function(t,e){function s(t,e){for(var s=-1,i=t.length;++s<i&&e(t[s],s,t)!==!1;);return t}t.exports=s},function(t,e,s){function i(t,e){return null==e?t:r(e,n(e),t)}var r=s(105),n=s(106);t.exports=i},function(t,e){function s(t,e,s){s||(s={});for(var i=-1,r=e.length;++i<r;){var n=e[i];s[n]=t[n]}return s}t.exports=s},function(t,e,s){var i=s(107),r=s(112),n=s(110),a=s(116),o=i(Object,"keys"),u=o?function(t){var e=null==t?void 0:t.constructor;return"function"==typeof e&&e.prototype===t||"function"!=typeof t&&r(t)?a(t):n(t)?o(t):[]}:a;t.exports=u},function(t,e,s){function i(t,e){var s=null==t?void 0:t[e];return r(s)?s:void 0}var r=s(108);t.exports=i},function(t,e,s){function i(t){return null==t?!1:r(t)?c.test(u.call(t)):n(t)&&a.test(t)}var r=s(109),n=s(111),a=/^\[object .+?Constructor\]$/,o=Object.prototype,u=Function.prototype.toString,p=o.hasOwnProperty,c=RegExp("^"+u.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=i},function(t,e,s){function i(t){return r(t)&&o.call(t)==n}var r=s(110),n="[object Function]",a=Object.prototype,o=a.toString;t.exports=i},function(t,e){function s(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}t.exports=s},function(t,e){function s(t){return!!t&&"object"==typeof t}t.exports=s},function(t,e,s){function i(t){return null!=t&&n(r(t))}var r=s(113),n=s(115);t.exports=i},function(t,e,s){var i=s(114),r=i("length");t.exports=r},function(t,e){function s(t){return function(e){return null==e?void 0:e[t]}}t.exports=s},function(t,e){function s(t){return"number"==typeof t&&t>-1&&t%1==0&&i>=t}var i=9007199254740991;t.exports=s},function(t,e,s){function i(t){for(var e=u(t),s=e.length,i=s&&t.length,p=!!i&&o(i)&&(n(t)||r(t)),l=-1,h=[];++l<s;){var f=e[l];(p&&a(f,i)||c.call(t,f))&&h.push(f)}return h}var r=s(117),n=s(118),a=s(119),o=s(115),u=s(120),p=Object.prototype,c=p.hasOwnProperty;t.exports=i},function(t,e,s){function i(t){return n(t)&&r(t)&&o.call(t,"callee")&&!u.call(t,"callee")}var r=s(112),n=s(111),a=Object.prototype,o=a.hasOwnProperty,u=a.propertyIsEnumerable;t.exports=i},function(t,e,s){var i=s(107),r=s(115),n=s(111),a="[object Array]",o=Object.prototype,u=o.toString,p=i(Array,"isArray"),c=p||function(t){return n(t)&&r(t.length)&&u.call(t)==a};t.exports=c},function(t,e){function s(t,e){return t="number"==typeof t||i.test(t)?+t:-1,e=null==e?r:e,t>-1&&t%1==0&&e>t}var i=/^\d+$/,r=9007199254740991;t.exports=s},function(t,e,s){function i(t){if(null==t)return[];u(t)||(t=Object(t));var e=t.length;e=e&&o(e)&&(n(t)||r(t))&&e||0;for(var s=t.constructor,i=-1,p="function"==typeof s&&s.prototype===t,l=Array(e),h=e>0;++i<e;)l[i]=i+"";for(var f in t)h&&a(f,e)||"constructor"==f&&(p||!c.call(t,f))||l.push(f);return l}var r=s(117),n=s(118),a=s(119),o=s(115),u=s(110),p=Object.prototype,c=p.hasOwnProperty;t.exports=i},function(t,e,s){function i(t,e){return r(t,e,n)}var r=s(122),n=s(106);t.exports=i},function(t,e,s){var i=s(123),r=i();t.exports=r},function(t,e,s){function i(t){return function(e,s,i){for(var n=r(e),a=i(e),o=a.length,u=t?o:-1;t?u--:++u<o;){var p=a[u];if(s(n[p],p,n)===!1)break}return e}}var r=s(124);t.exports=i},function(t,e,s){function i(t){return r(t)?t:Object(t)}var r=s(110);t.exports=i},function(t,e){function s(t){var e=t.length,s=new t.constructor(e);return e&&"string"==typeof t[0]&&r.call(t,"index")&&(s.index=t.index,s.input=t.input),s}var i=Object.prototype,r=i.hasOwnProperty;t.exports=s},function(t,e,s){function i(t,e,s){var i=t.constructor;switch(e){case c:return r(t);case n:case a:return new i(+t);case l:case h:case f:case d:case y:case m:case v:case g:case x:var b=t.buffer;return new i(s?r(b):b,t.byteOffset,t.length);case o:case p:return new i(t);case u:var E=new i(t.source,A.exec(t));E.lastIndex=t.lastIndex}return E}var r=s(127),n="[object Boolean]",a="[object Date]",o="[object Number]",u="[object RegExp]",p="[object String]",c="[object ArrayBuffer]",l="[object Float32Array]",h="[object Float64Array]",f="[object Int8Array]",d="[object Int16Array]",y="[object Int32Array]",m="[object Uint8Array]",v="[object Uint8ClampedArray]",g="[object Uint16Array]",x="[object Uint32Array]",A=/\w*$/;t.exports=i},function(t,e){(function(e){function s(t){var e=new i(t.byteLength),s=new r(e);return s.set(new r(t)),e}var i=e.ArrayBuffer,r=e.Uint8Array;t.exports=s}).call(e,function(){return this}())},function(t,e){function s(t){var e=t.constructor;return"function"==typeof e&&e instanceof e||(e=Object),new e}t.exports=s},function(t,e,s){function i(t,e,s){if("function"!=typeof t)return r;if(void 0===e)return t;switch(s){case 1:return function(s){return t.call(e,s)};case 3:return function(s,i,r){return t.call(e,s,i,r)};case 4:return function(s,i,r,n){return t.call(e,s,i,r,n)};case 5:return function(s,i,r,n,a){return t.call(e,s,i,r,n,a)}}return function(){return t.apply(e,arguments)}}var r=s(130);t.exports=i},function(t,e){function s(t){return t}t.exports=s},function(t,e,s){function i(t,e,s){if(!a(s))return!1;var i=typeof e;if("number"==i?r(s)&&n(e,s.length):"string"==i&&e in s){var o=s[e];return t===t?t===o:o!==o}return!1}var r=s(112),n=s(119),a=s(110);t.exports=i},function(t,e,s){t.exports=s(133)},function(t,e,s){var i=s(103),r=s(134),n=s(136),a=n(i,r);t.exports=a},function(t,e,s){var i=s(121),r=s(135),n=r(i);t.exports=n},function(t,e,s){function i(t,e){return function(s,i){var o=s?r(s):0;if(!n(o))return t(s,i);for(var u=e?o:-1,p=a(s);(e?u--:++u<o)&&i(p[u],u,p)!==!1;);return s}}var r=s(113),n=s(115),a=s(124);t.exports=i},function(t,e,s){function i(t,e){return function(s,i,a){return"function"==typeof i&&void 0===a&&n(s)?t(s,i):e(s,r(i,a,3))}}var r=s(129),n=s(118);t.exports=i},function(t,e,s){function i(t,e,s,i){var u=t?t.length:0;return u?(null!=e&&"boolean"!=typeof e&&(i=s,s=a(t,e,i)?void 0:e,e=!1),s=null==s?s:r(s,i,3),e?o(t,s):n(t,s)):[]}var r=s(138),n=s(160),a=s(131),o=s(167);t.exports=i},function(t,e,s){function i(t,e,s){var i=typeof t;return"function"==i?void 0===e?t:a(t,e,s):null==t?o:"object"==i?r(t):void 0===e?u(t):n(t,e)}var r=s(139),n=s(151),a=s(129),o=s(130),u=s(158);t.exports=i},function(t,e,s){function i(t){var e=n(t);if(1==e.length&&e[0][2]){var s=e[0][0],i=e[0][1];return function(t){return null==t?!1:t[s]===i&&(void 0!==i||s in a(t))}}return function(t){return r(t,e)}}var r=s(140),n=s(148),a=s(124);t.exports=i},function(t,e,s){function i(t,e,s){var i=e.length,a=i,o=!s;if(null==t)return!a;for(t=n(t);i--;){var u=e[i];if(o&&u[2]?u[1]!==t[u[0]]:!(u[0]in t))return!1}for(;++i<a;){u=e[i];var p=u[0],c=t[p],l=u[1];if(o&&u[2]){if(void 0===c&&!(p in t))return!1}else{var h=s?s(c,l,p):void 0;if(!(void 0===h?r(l,c,s,!0):h))return!1}}return!0}var r=s(141),n=s(124);t.exports=i},function(t,e,s){function i(t,e,s,o,u,p){return t===e?!0:null==t||null==e||!n(t)&&!a(e)?t!==t&&e!==e:r(t,e,i,s,o,u,p)}var r=s(142),n=s(110),a=s(111);t.exports=i},function(t,e,s){function i(t,e,s,i,h,y,m){var v=o(t),g=o(e),x=c,A=c;v||(x=d.call(t),x==p?x=l:x!=l&&(v=u(t))),g||(A=d.call(e),A==p?A=l:A!=l&&(g=u(e)));var b=x==l,E=A==l,C=x==A;if(C&&!v&&!b)return n(t,e,x);if(!h){var D=b&&f.call(t,"__wrapped__"),S=E&&f.call(e,"__wrapped__");if(D||S)return s(D?t.value():t,S?e.value():e,i,h,y,m)}if(!C)return!1;y||(y=[]),m||(m=[]);for(var F=y.length;F--;)if(y[F]==t)return m[F]==e;y.push(t),m.push(e);var w=(v?r:a)(t,e,s,i,h,y,m);return y.pop(),m.pop(),w}var r=s(143),n=s(145),a=s(146),o=s(118),u=s(147),p="[object Arguments]",c="[object Array]",l="[object Object]",h=Object.prototype,f=h.hasOwnProperty,d=h.toString;t.exports=i},function(t,e,s){function i(t,e,s,i,n,a,o){var u=-1,p=t.length,c=e.length;if(p!=c&&!(n&&c>p))return!1;for(;++u<p;){var l=t[u],h=e[u],f=i?i(n?h:l,n?l:h,u):void 0;if(void 0!==f){if(f)continue;return!1}if(n){if(!r(e,function(t){return l===t||s(l,t,i,n,a,o)}))return!1}else if(l!==h&&!s(l,h,i,n,a,o))return!1}return!0}var r=s(144);t.exports=i},function(t,e){function s(t,e){for(var s=-1,i=t.length;++s<i;)if(e(t[s],s,t))return!0;return!1}t.exports=s},function(t,e){function s(t,e,s){switch(s){case i:case r:return+t==+e;case n:return t.name==e.name&&t.message==e.message;case a:return t!=+t?e!=+e:t==+e;case o:case u:return t==e+""}return!1}var i="[object Boolean]",r="[object Date]",n="[object Error]",a="[object Number]",o="[object RegExp]",u="[object String]";t.exports=s},function(t,e,s){function i(t,e,s,i,n,o,u){var p=r(t),c=p.length,l=r(e),h=l.length;if(c!=h&&!n)return!1;for(var f=c;f--;){var d=p[f];if(!(n?d in e:a.call(e,d)))return!1}for(var y=n;++f<c;){d=p[f];var m=t[d],v=e[d],g=i?i(n?v:m,n?m:v,d):void 0;if(!(void 0===g?s(m,v,i,n,o,u):g))return!1;y||(y="constructor"==d)}if(!y){var x=t.constructor,A=e.constructor;if(x!=A&&"constructor"in t&&"constructor"in e&&!("function"==typeof x&&x instanceof x&&"function"==typeof A&&A instanceof A))return!1}return!0}var r=s(106),n=Object.prototype,a=n.hasOwnProperty;t.exports=i},function(t,e,s){function i(t){return n(t)&&r(t.length)&&!!k[_.call(t)]}var r=s(115),n=s(111),a="[object Arguments]",o="[object Array]",u="[object Boolean]",p="[object Date]",c="[object Error]",l="[object Function]",h="[object Map]",f="[object Number]",d="[object Object]",y="[object RegExp]",m="[object Set]",v="[object String]",g="[object WeakMap]",x="[object ArrayBuffer]",A="[object Float32Array]",b="[object Float64Array]",E="[object Int8Array]",C="[object Int16Array]",D="[object Int32Array]",S="[object Uint8Array]",F="[object Uint8ClampedArray]",w="[object Uint16Array]",T="[object Uint32Array]",k={}; k[A]=k[b]=k[E]=k[C]=k[D]=k[S]=k[F]=k[w]=k[T]=!0,k[a]=k[o]=k[x]=k[u]=k[p]=k[c]=k[l]=k[h]=k[f]=k[d]=k[y]=k[m]=k[v]=k[g]=!1;var P=Object.prototype,_=P.toString;t.exports=i},function(t,e,s){function i(t){for(var e=n(t),s=e.length;s--;)e[s][2]=r(e[s][1]);return e}var r=s(149),n=s(150);t.exports=i},function(t,e,s){function i(t){return t===t&&!r(t)}var r=s(110);t.exports=i},function(t,e,s){function i(t){t=n(t);for(var e=-1,s=r(t),i=s.length,a=Array(i);++e<i;){var o=s[e];a[e]=[o,t[o]]}return a}var r=s(106),n=s(124);t.exports=i},function(t,e,s){function i(t,e){var s=o(t),i=u(t)&&p(e),f=t+"";return t=h(t),function(o){if(null==o)return!1;var u=f;if(o=l(o),(s||!i)&&!(u in o)){if(o=1==t.length?o:r(o,a(t,0,-1)),null==o)return!1;u=c(t),o=l(o)}return o[u]===e?void 0!==e||u in o:n(e,o[u],void 0,!0)}}var r=s(152),n=s(141),a=s(153),o=s(118),u=s(154),p=s(149),c=s(155),l=s(124),h=s(156);t.exports=i},function(t,e,s){function i(t,e,s){if(null!=t){void 0!==s&&s in r(t)&&(e=[s]);for(var i=0,n=e.length;null!=t&&n>i;)t=t[e[i++]];return i&&i==n?t:void 0}}var r=s(124);t.exports=i},function(t,e){function s(t,e,s){var i=-1,r=t.length;e=null==e?0:+e||0,0>e&&(e=-e>r?0:r+e),s=void 0===s||s>r?r:+s||0,0>s&&(s+=r),r=e>s?0:s-e>>>0,e>>>=0;for(var n=Array(r);++i<r;)n[i]=t[i+e];return n}t.exports=s},function(t,e,s){function i(t,e){var s=typeof t;if("string"==s&&o.test(t)||"number"==s)return!0;if(r(t))return!1;var i=!a.test(t);return i||null!=e&&t in n(e)}var r=s(118),n=s(124),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,o=/^\w*$/;t.exports=i},function(t,e){function s(t){var e=t?t.length:0;return e?t[e-1]:void 0}t.exports=s},function(t,e,s){function i(t){if(n(t))return t;var e=[];return r(t).replace(a,function(t,s,i,r){e.push(i?r.replace(o,"$1"):s||t)}),e}var r=s(157),n=s(118),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,o=/\\(\\)?/g;t.exports=i},function(t,e){function s(t){return null==t?"":t+""}t.exports=s},function(t,e,s){function i(t){return a(t)?r(t):n(t)}var r=s(114),n=s(159),a=s(154);t.exports=i},function(t,e,s){function i(t){var e=t+"";return t=n(t),function(s){return r(s,t,e)}}var r=s(152),n=s(156);t.exports=i},function(t,e,s){function i(t,e){var s=-1,i=r,u=t.length,p=!0,c=p&&u>=o,l=c?a():null,h=[];l?(i=n,p=!1):(c=!1,l=e?[]:h);t:for(;++s<u;){var f=t[s],d=e?e(f,s,t):f;if(p&&f===f){for(var y=l.length;y--;)if(l[y]===d)continue t;e&&l.push(d),h.push(f)}else i(l,d,0)<0&&((e||c)&&l.push(d),h.push(f))}return h}var r=s(161),n=s(163),a=s(164),o=200;t.exports=i},function(t,e,s){function i(t,e,s){if(e!==e)return r(t,s);for(var i=s-1,n=t.length;++i<n;)if(t[i]===e)return i;return-1}var r=s(162);t.exports=i},function(t,e){function s(t,e,s){for(var i=t.length,r=e+(s?0:-1);s?r--:++r<i;){var n=t[r];if(n!==n)return r}return-1}t.exports=s},function(t,e,s){function i(t,e){var s=t.data,i="string"==typeof e||r(e)?s.set.has(e):s.hash[e];return i?0:-1}var r=s(110);t.exports=i},function(t,e,s){(function(e){function i(t){return o&&a?new r(t):null}var r=s(165),n=s(107),a=n(e,"Set"),o=n(Object,"create");t.exports=i}).call(e,function(){return this}())},function(t,e,s){(function(e){function i(t){var e=t?t.length:0;for(this.data={hash:o(null),set:new a};e--;)this.push(t[e])}var r=s(166),n=s(107),a=n(e,"Set"),o=n(Object,"create");i.prototype.push=r,t.exports=i}).call(e,function(){return this}())},function(t,e,s){function i(t){var e=this.data;"string"==typeof t||r(t)?e.set.add(t):e.hash[t]=!0}var r=s(110);t.exports=i},function(t,e){function s(t,e){for(var s,i=-1,r=t.length,n=-1,a=[];++i<r;){var o=t[i],u=e?e(o,i,t):o;i&&s===u||(s=u,a[++n]=o)}return a}t.exports=s},function(t,e,s){"use strict";s(169),s(170),s(178),s(179),s(180),s(181),s(182)},function(t,e,s){"use strict";function i(t){return Array.isArray(t)?"array":null===t?"null":void 0===t?"undefined":typeof t}function r(t){function e(e,s,i){if(Array.isArray(i))for(var r=0;r<i.length;r++)t(e,s+"["+r+"]",i[r])}return e.each=t,e}function n(){function t(t,e,i){if(s.indexOf(i)<0)throw new TypeError("Property "+e+" expected value to be one of "+JSON.stringify(s)+" but got "+JSON.stringify(i))}for(var e=arguments.length,s=Array(e),i=0;e>i;i++)s[i]=arguments[i];return t.oneOf=s,t}function a(){function t(t,e,i){for(var r=!1,n=s,a=Array.isArray(n),o=0,n=a?n:l(n);;){var u;if(a){if(o>=n.length)break;u=n[o++]}else{if(o=n.next(),o.done)break;u=o.value}var p=u;if(d.is(p,i)){r=!0;break}}if(!r)throw new TypeError("Property "+e+" of "+t.type+" expected node to be of a type "+JSON.stringify(s)+" but instead got "+JSON.stringify(i&&i.type))}for(var e=arguments.length,s=Array(e),i=0;e>i;i++)s[i]=arguments[i];return t.oneOfNodeTypes=s,t}function o(){function t(t,e,r){for(var n=!1,a=s,o=Array.isArray(a),u=0,a=o?a:l(a);;){var p;if(o){if(u>=a.length)break;p=a[u++]}else{if(u=a.next(),u.done)break;p=u.value}var c=p;if(i(r)===c||d.is(c,r)){n=!0;break}}if(!n)throw new TypeError("Property "+e+" of "+t.type+" expected node to be of a type "+JSON.stringify(s)+" but instead got "+JSON.stringify(r&&r.type))}for(var e=arguments.length,s=Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.oneOfNodeOrValueTypes=s,t}function u(t){function e(e,s,r){var n=i(r)===t;if(!n)throw new TypeError("Property "+s+" expected type of "+t+" but got "+i(r))}return e.type=t,e}function p(){function t(){for(var t=s,e=Array.isArray(t),i=0,t=e?t:l(t);;){var r;if(e){if(i>=t.length)break;r=t[i++]}else{if(i=t.next(),i.done)break;r=i.value}var n=r;n.apply(void 0,arguments)}}for(var e=arguments.length,s=Array(e),i=0;e>i;i++)s[i]=arguments[i];return t.chainOf=s,t}function c(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],s=e.inherits&&A[e.inherits]||{};e.fields=e.fields||s.fields||{},e.visitor=e.visitor||s.visitor||[],e.aliases=e.aliases||s.aliases||[],e.builder=e.builder||s.builder||e.visitor||[],e.deprecatedAlias&&(x[e.deprecatedAlias]=t);for(var r=e.visitor.concat(e.builder),n=Array.isArray(r),a=0,r=n?r:l(r);;){var o;if(n){if(a>=r.length)break;o=r[a++]}else{if(a=r.next(),a.done)break;o=a.value}var p=o;e.fields[p]=e.fields[p]||{}}for(var p in e.fields){var c=e.fields[p];void 0===c["default"]?c["default"]=null:c.validate||(c.validate=u(i(c["default"])))}y[t]=e.visitor,g[t]=e.builder,v[t]=e.fields,m[t]=e.aliases,A[t]=e}var l=s(54)["default"],h=s(86)["default"];e.__esModule=!0,e.assertEach=r,e.assertOneOf=n,e.assertNodeType=a,e.assertNodeOrValueType=o,e.assertValueType=u,e.chain=p,e["default"]=c;var f=s(41),d=h(f),y={};e.VISITOR_KEYS=y;var m={};e.ALIAS_KEYS=m;var v={};e.NODE_FIELDS=v;var g={};e.BUILDER_KEYS=g;var x={};e.DEPRECATED_KEYS=x;var A={}},function(t,e,s){"use strict";var i=s(86)["default"],r=s(85)["default"],n=s(41),a=i(n),o=s(171),u=s(169),p=r(u);p["default"]("ArrayExpression",{fields:{elements:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeOrValueType("null","Expression","SpreadElement"))),"default":[]}},visitor:["elements"],aliases:["Expression"]}),p["default"]("AssignmentExpression",{fields:{operator:{validate:u.assertValueType("string")},left:{validate:u.assertNodeType("LVal")},right:{validate:u.assertNodeType("Expression")}},builder:["operator","left","right"],visitor:["left","right"],aliases:["Expression"]}),p["default"]("BinaryExpression",{builder:["operator","left","right"],fields:{operator:{validate:u.assertOneOf.apply(void 0,o.BINARY_OPERATORS)},left:{validate:u.assertNodeType("Expression")},right:{validate:u.assertNodeType("Expression")}},visitor:["left","right"],aliases:["Binary","Expression"]}),p["default"]("Directive",{visitor:["value"],fields:{value:{validate:u.assertNodeType("DirectiveLiteral")}}}),p["default"]("DirectiveLiteral",{builder:["value"],fields:{value:{validate:u.assertValueType("string")}}}),p["default"]("BlockStatement",{builder:["body","directives"],visitor:["directives","body"],fields:{directives:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Directive"))),"default":[]},body:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Statement")))}},aliases:["Scopable","BlockParent","Block","Statement"]}),p["default"]("BreakStatement",{visitor:["label"],fields:{label:{validate:u.assertNodeType("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),p["default"]("CallExpression",{visitor:["callee","arguments"],fields:{callee:{validate:u.assertNodeType("Expression")},arguments:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Expression","SpreadElement")))}},aliases:["Expression"]}),p["default"]("CatchClause",{visitor:["param","body"],fields:{param:{validate:u.assertNodeType("Identifier")},body:{validate:u.assertNodeType("BlockStatement")}},aliases:["Scopable"]}),p["default"]("ConditionalExpression",{visitor:["test","consequent","alternate"],fields:{test:{validate:u.assertNodeType("Expression")},consequent:{validate:u.assertNodeType("Expression")},alternate:{validate:u.assertNodeType("Expression")}},aliases:["Expression","Conditional"]}),p["default"]("ContinueStatement",{visitor:["label"],fields:{label:{validate:u.assertNodeType("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),p["default"]("DebuggerStatement",{aliases:["Statement"]}),p["default"]("DoWhileStatement",{visitor:["test","body"],fields:{test:{validate:u.assertNodeType("Expression")},body:{validate:u.assertNodeType("Statement")}},aliases:["Statement","BlockParent","Loop","While","Scopable"]}),p["default"]("EmptyStatement",{aliases:["Statement"]}),p["default"]("ExpressionStatement",{visitor:["expression"],fields:{expression:{validate:u.assertNodeType("Expression")}},aliases:["Statement","ExpressionWrapper"]}),p["default"]("File",{builder:["program","comments","tokens"],visitor:["program"],fields:{program:{validate:u.assertNodeType("Program")}}}),p["default"]("ForInStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:u.assertNodeType("VariableDeclaration","LVal")},right:{validate:u.assertNodeType("Expression")},body:{validate:u.assertNodeType("Statement")}}}),p["default"]("ForStatement",{visitor:["init","test","update","body"],aliases:["Scopable","Statement","For","BlockParent","Loop"],fields:{init:{validate:u.assertNodeType("VariableDeclaration","Expression"),optional:!0},test:{validate:u.assertNodeType("Expression"),optional:!0},update:{validate:u.assertNodeType("Expression"),optional:!0},body:{validate:u.assertNodeType("Statement")}}}),p["default"]("FunctionDeclaration",{builder:["id","params","body","generator","async"],visitor:["id","params","body","returnType","typeParameters"],fields:{id:{validate:u.assertNodeType("Identifier")},params:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("LVal")))},body:{validate:u.assertNodeType("BlockStatement")},generator:{"default":!1,validate:u.assertValueType("boolean")},async:{"default":!1,validate:u.assertValueType("boolean")}},aliases:["Scopable","Function","BlockParent","FunctionParent","Statement","Pureish","Declaration"]}),p["default"]("FunctionExpression",{inherits:"FunctionDeclaration",aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{id:{validate:u.assertNodeType("Identifier"),optional:!0},params:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("LVal")))},body:{validate:u.assertNodeType("BlockStatement")},generator:{"default":!1,validate:u.assertValueType("boolean")},async:{"default":!1,validate:u.assertValueType("boolean")}}}),p["default"]("Identifier",{builder:["name"],visitor:["typeAnnotation"],aliases:["Expression","LVal"],fields:{name:{validate:function(t,e,s){!a.isValidIdentifier(s)}}}}),p["default"]("IfStatement",{visitor:["test","consequent","alternate"],aliases:["Statement","Conditional"],fields:{test:{validate:u.assertNodeType("Expression")},consequent:{validate:u.assertNodeType("Statement")},alternate:{optional:!0,validate:u.assertNodeType("Statement")}}}),p["default"]("LabeledStatement",{visitor:["label","body"],aliases:["Statement"],fields:{label:{validate:u.assertNodeType("Identifier")},body:{validate:u.assertNodeType("Statement")}}}),p["default"]("StringLiteral",{builder:["value"],fields:{value:{validate:u.assertValueType("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),p["default"]("NumericLiteral",{builder:["value"],deprecatedAlias:"NumberLiteral",fields:{value:{validate:u.assertValueType("number")}},aliases:["Expression","Pureish","Literal","Immutable"]}),p["default"]("NullLiteral",{aliases:["Expression","Pureish","Literal","Immutable"]}),p["default"]("BooleanLiteral",{builder:["value"],fields:{value:{validate:u.assertValueType("boolean")}},aliases:["Expression","Pureish","Literal","Immutable"]}),p["default"]("RegExpLiteral",{builder:["pattern","flags"],deprecatedAlias:"RegexLiteral",aliases:["Expression","Literal"],fields:{pattern:{validate:u.assertValueType("string")},flags:{validate:u.assertValueType("string"),"default":""}}}),p["default"]("LogicalExpression",{builder:["operator","left","right"],visitor:["left","right"],aliases:["Binary","Expression"],fields:{operator:{validate:u.assertOneOf.apply(void 0,o.LOGICAL_OPERATORS)},left:{validate:u.assertNodeType("Expression")},right:{validate:u.assertNodeType("Expression")}}}),p["default"]("MemberExpression",{builder:["object","property","computed"],visitor:["object","property"],aliases:["Expression","LVal"],fields:{object:{validate:u.assertNodeType("Expression")},property:{validate:function(t,e,s){var i=t.computed?"Expression":"Identifier";u.assertNodeType(i)(t,e,s)}},computed:{"default":!1}}}),p["default"]("NewExpression",{visitor:["callee","arguments"],aliases:["Expression"],fields:{callee:{validate:u.assertNodeType("Expression")},arguments:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Expression","SpreadElement")))}}}),p["default"]("Program",{visitor:["directives","body"],builder:["body","directives"],fields:{directives:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Directive"))),"default":[]},body:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Statement")))}},aliases:["Scopable","BlockParent","Block","FunctionParent"]}),p["default"]("ObjectExpression",{visitor:["properties"],aliases:["Expression"],fields:{properties:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("ObjectMethod","ObjectProperty","SpreadProperty")))}}}),p["default"]("ObjectMethod",{builder:["kind","key","params","body","computed"],fields:{kind:{validate:u.chain(u.assertValueType("string"),u.assertOneOf("method","get","set")),"default":"method"},computed:{validate:u.assertValueType("boolean"),"default":!1},key:{validate:function(t,e,s){var i=t.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];u.assertNodeType.apply(void 0,i)(t,e,s)}},decorators:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Decorator")))},body:{validate:u.assertNodeType("BlockStatement")},generator:{"default":!1,validate:u.assertValueType("boolean")},async:{"default":!1,validate:u.assertValueType("boolean")}},visitor:["key","params","body","decorators","returnType","typeParameters"],aliases:["UserWhitespacable","Function","Scopable","BlockParent","FunctionParent","Method","ObjectMember"]}),p["default"]("ObjectProperty",{builder:["key","value","computed","shorthand","decorators"],fields:{computed:{validate:u.assertValueType("boolean"),"default":!1},key:{validate:function(t,e,s){var i=t.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];u.assertNodeType.apply(void 0,i)(t,e,s)}},value:{validate:u.assertNodeType("Expression")},shorthand:{validate:u.assertValueType("boolean"),"default":!1},decorators:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Decorator"))),optional:!0}},visitor:["key","value","decorators"],aliases:["UserWhitespacable","Property","ObjectMember"]}),p["default"]("RestElement",{visitor:["argument","typeAnnotation"],aliases:["LVal"],fields:{argument:{validate:u.assertNodeType("LVal")}}}),p["default"]("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:u.assertNodeType("Expression"),optional:!0}}}),p["default"]("SequenceExpression",{visitor:["expressions"],fields:{expressions:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Expression")))}},aliases:["Expression"]}),p["default"]("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:u.assertNodeType("Expression"),optional:!0},consequent:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("Statement")))}}}),p["default"]("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:u.assertNodeType("Expression")},cases:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("SwitchCase")))}}}),p["default"]("ThisExpression",{aliases:["Expression"]}),p["default"]("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:u.assertNodeType("Expression")}}}),p["default"]("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{body:{validate:u.assertNodeType("BlockStatement")},handler:{optional:!0,handler:u.assertNodeType("BlockStatement")},finalizer:{optional:!0,validate:u.assertNodeType("BlockStatement")}}}),p["default"]("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{"default":!1},argument:{validate:u.assertNodeType("Expression")},operator:{validate:u.assertOneOf.apply(void 0,o.UNARY_OPERATORS)}},visitor:["argument"],aliases:["UnaryLike","Expression"]}),p["default"]("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{"default":!1},argument:{validate:u.assertNodeType("Expression")},operator:{validate:u.assertOneOf.apply(void 0,o.UPDATE_OPERATORS)}},visitor:["argument"],aliases:["Expression"]}),p["default"]("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{kind:{validate:u.chain(u.assertValueType("string"),u.assertOneOf("var","let","const"))},declarations:{validate:u.chain(u.assertValueType("array"),u.assertEach(u.assertNodeType("VariableDeclarator")))}}}),p["default"]("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:u.assertNodeType("LVal")},init:{optional:!0,validate:u.assertNodeType("Expression")}}}),p["default"]("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:u.assertNodeType("Expression")},body:{validate:u.assertNodeType("BlockStatement","Statement")}}}),p["default"]("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{object:u.assertNodeType("Expression")},body:{validate:u.assertNodeType("BlockStatement")}}})},function(t,e,s){"use strict";var i=s(172)["default"];e.__esModule=!0;var r=["consequent","body","alternate"];e.STATEMENT_OR_BLOCK_KEYS=r;var n=["body","expressions"];e.FLATTENABLE_KEYS=n;var a=["left","init"];e.FOR_INIT_KEYS=a;var o=["leadingComments","trailingComments","innerComments"];e.COMMENT_KEYS=o;var u=["||","&&"];e.LOGICAL_OPERATORS=u;var p=["++","--"];e.UPDATE_OPERATORS=p;var c=[">","<",">=","<="];e.BOOLEAN_NUMBER_BINARY_OPERATORS=c;var l=["==","===","!=","!=="];e.EQUALITY_BINARY_OPERATORS=l;var h=[].concat(l,["in","instanceof"]);e.COMPARISON_BINARY_OPERATORS=h;var f=[].concat(h,c);e.BOOLEAN_BINARY_OPERATORS=f;var d=["-","/","%","*","**","&","|",">>",">>>","<<","^"];e.NUMBER_BINARY_OPERATORS=d;var y=["+"].concat(d,f);e.BINARY_OPERATORS=y;var m=["delete","!"];e.BOOLEAN_UNARY_OPERATORS=m;var v=["+","-","++","--","~"];e.NUMBER_UNARY_OPERATORS=v;var g=["typeof"];e.STRING_UNARY_OPERATORS=g;var x=["void"].concat(m,v,g);e.UNARY_OPERATORS=x;var A={optional:["typeAnnotation","typeParameters","returnType"],force:["start","loc","end"]};e.INHERIT_KEYS=A;var b=i("var used to be block scoped");e.BLOCK_SCOPED_SYMBOL=b;var E=i("should not be considered a local binding");e.NOT_LOCAL_BINDING=E},function(t,e,s){t.exports={"default":s(173),__esModule:!0}},function(t,e,s){s(174),t.exports=s(50).Symbol["for"]},function(t,e,s){"use strict";var i=s(68),r=s(49),n=s(71),a=s(70),o=s(48),u=s(66),p=s(53),c=s(75),l=s(73),h=s(76),f=s(74),d=s(175),y=s(91),m=s(176),v=s(177),g=s(81),x=s(61),A=s(69),b=i.getDesc,E=i.setDesc,C=i.create,D=y.get,S=r.Symbol,F=r.JSON,w=F&&F.stringify,T=!1,k=f("_hidden"),P=i.isEnum,_=c("symbol-registry"),B=c("symbols"),N="function"==typeof S,L=Object.prototype,I=a&&p(function(){return 7!=C(E({},"a",{get:function(){return E(this,"a",{value:7}).a}})).a})?function(t,e,s){var i=b(L,e);i&&delete L[e],E(t,e,s),i&&t!==L&&E(L,e,i)}:E,O=function(t){var e=B[t]=C(S.prototype);return e._k=t,a&&T&&I(L,t,{configurable:!0,set:function(e){n(this,k)&&n(this[k],t)&&(this[k][t]=!1),I(this,t,A(1,e))}}),e},M=function(t){return"symbol"==typeof t},j=function(t,e,s){return s&&n(B,e)?(s.enumerable?(n(t,k)&&t[k][e]&&(t[k][e]=!1),s=C(s,{enumerable:A(0,!1)})):(n(t,k)||E(t,k,A(1,{})),t[k][e]=!0),I(t,e,s)):E(t,e,s)},R=function(t,e){g(t);for(var s,i=m(e=x(e)),r=0,n=i.length;n>r;)j(t,s=i[r++],e[s]);return t},V=function(t,e){return void 0===e?C(t):R(C(t),e)},$=function(t){var e=P.call(this,t);return e||!n(this,t)||!n(B,t)||n(this,k)&&this[k][t]?e:!0},G=function(t,e){var s=b(t=x(t),e);return!s||!n(B,e)||n(t,k)&&t[k][e]||(s.enumerable=!0),s},q=function(t){for(var e,s=D(x(t)),i=[],r=0;s.length>r;)n(B,e=s[r++])||e==k||i.push(e);return i},U=function(t){for(var e,s=D(x(t)),i=[],r=0;s.length>r;)n(B,e=s[r++])&&i.push(B[e]);return i},W=function(t){if(void 0!==t&&!M(t)){for(var e,s,i=[t],r=1,n=arguments;n.length>r;)i.push(n[r++]);return e=i[1],"function"==typeof e&&(s=e),(s||!v(e))&&(e=function(t,e){return s&&(e=s.call(this,t,e)),M(e)?void 0:e}),i[1]=e,w.apply(F,i)}},X=p(function(){var t=S();return"[null]"!=w([t])||"{}"!=w({a:t})||"{}"!=w(Object(t))});N||(S=function(){if(M(this))throw TypeError("Symbol is not a constructor");return O(h(arguments.length>0?arguments[0]:void 0))},u(S.prototype,"toString",function(){return this._k}),M=function(t){return t instanceof S},i.create=V,i.isEnum=$,i.getDesc=G,i.setDesc=j,i.setDescs=R,i.getNames=y.get=q,i.getSymbols=U,a&&!s(65)&&u(L,"propertyIsEnumerable",$,!0));var J={"for":function(t){return n(_,t+="")?_[t]:_[t]=S(t)},keyFor:function(t){return d(_,t)},useSetter:function(){T=!0},useSimple:function(){T=!1}};i.each.call("hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),function(t){var e=f(t);J[t]=N?e:O(e)}),T=!0,o(o.G+o.W,{Symbol:S}),o(o.S,"Symbol",J),o(o.S+o.F*!N,"Object",{create:V,defineProperty:j,defineProperties:R,getOwnPropertyDescriptor:G,getOwnPropertyNames:q,getOwnPropertySymbols:U}),F&&o(o.S+o.F*(!N||X),"JSON",{stringify:W}),l(S,"Symbol"),l(Math,"Math",!0),l(r.JSON,"JSON",!0)},function(t,e,s){var i=s(68),r=s(61);t.exports=function(t,e){for(var s,n=r(t),a=i.getKeys(n),o=a.length,u=0;o>u;)if(n[s=a[u++]]===e)return s}},function(t,e,s){var i=s(68);t.exports=function(t){var e=i.getKeys(t),s=i.getSymbols;if(s)for(var r,n=s(t),a=i.isEnum,o=0;n.length>o;)a.call(t,r=n[o++])&&e.push(r);return e}},function(t,e,s){var i=s(63);t.exports=Array.isArray||function(t){return"Array"==i(t)}},function(t,e,s){"use strict";var i=s(85)["default"],r=s(169),n=i(r);n["default"]("AssignmentPattern",{visitor:["left","right"],aliases:["Pattern","LVal"],fields:{left:{validate:r.assertNodeType("Identifier")},right:{validate:r.assertNodeType("Expression")}}}),n["default"]("ArrayPattern",{visitor:["elements","typeAnnotation"],aliases:["Pattern","LVal"],fields:{elements:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("Expression")))}}}),n["default"]("ArrowFunctionExpression",{builder:["params","body","async"],visitor:["params","body","returnType"],aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{params:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("LVal")))},body:{validate:r.assertNodeType("BlockStatement","Expression")},async:{validate:r.assertValueType("boolean"),"default":!1}}}),n["default"]("ClassBody",{visitor:["body"],fields:{body:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("ClassMethod","ClassProperty")))}}}),n["default"]("ClassDeclaration",{builder:["id","superClass","body","decorators"],visitor:["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators"],aliases:["Scopable","Class","Statement","Declaration","Pureish"],fields:{id:{validate:r.assertNodeType("Identifier")},body:{validate:r.assertNodeType("ClassBody")},superClass:{optional:!0,validate:r.assertNodeType("Expression")},decorators:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("Decorator")))}}}),n["default"]("ClassExpression",{inherits:"ClassDeclaration",aliases:["Scopable","Class","Expression","Pureish"],fields:{id:{optional:!0,validate:r.assertNodeType("Identifier")},body:{validate:r.assertNodeType("ClassBody")},superClass:{optional:!0,validate:r.assertNodeType("Expression")},decorators:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("Decorator")))}}}),n["default"]("ExportAllDeclaration",{visitor:["source"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{source:{validate:r.assertNodeType("StringLiteral")}}}),n["default"]("ExportDefaultDeclaration",{visitor:["declaration"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{declaration:{validate:r.assertNodeType("FunctionDeclaration","ClassDeclaration","Expression")}}}),n["default"]("ExportNamedDeclaration",{visitor:["declaration","specifiers","source"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{declaration:{validate:r.assertNodeType("Declaration"),optional:!0},specifiers:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("ExportSpecifier")))},source:{validate:r.assertNodeType("StringLiteral"),optional:!0}}}),n["default"]("ExportSpecifier",{visitor:["local","exported"],aliases:["ModuleSpecifier"],fields:{local:{validate:r.assertNodeType("Identifier")},imported:{validate:r.assertNodeType("Identifier")}}}),n["default"]("ForOfStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:r.assertNodeType("VariableDeclaration","LVal")},right:{validate:r.assertNodeType("Expression")},body:{validate:r.assertNodeType("Statement")}}}),n["default"]("ImportDeclaration",{visitor:["specifiers","source"],aliases:["Statement","Declaration","ModuleDeclaration"],fields:{specifiers:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier")))},source:{validate:r.assertNodeType("StringLiteral")}}}),n["default"]("ImportDefaultSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:r.assertNodeType("Identifier")}}}),n["default"]("ImportNamespaceSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:r.assertNodeType("Identifier")}}}),n["default"]("ImportSpecifier",{visitor:["local","imported"],aliases:["ModuleSpecifier"],fields:{local:{validate:r.assertNodeType("Identifier")},imported:{validate:r.assertNodeType("Identifier")}}}),n["default"]("MetaProperty",{visitor:["meta","property"],aliases:["Expression"],fields:{meta:{validate:r.assertValueType("string")},property:{validate:r.assertValueType("string")}}}),n["default"]("ClassMethod",{aliases:["Function","Scopable","BlockParent","FunctionParent","Method"],builder:["kind","key","params","body","computed","static"],visitor:["key","params","body","decorators","returnType","typeParameters"],fields:{kind:{validate:r.chain(r.assertValueType("string"),r.assertOneOf("get","set","method","constructor")),"default":"method"},computed:{"default":!1,validate:r.assertValueType("boolean")},"static":{"default":!1,validate:r.assertValueType("boolean")},key:{validate:function(t,e,s){var i=t.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];r.assertNodeType.apply(void 0,i)(t,e,s)}},params:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("LVal")))},body:{validate:r.assertNodeType("BlockStatement")},generator:{"default":!1,validate:r.assertValueType("boolean")},async:{"default":!1,validate:r.assertValueType("boolean")}}}),n["default"]("ObjectPattern",{visitor:["properties","typeAnnotation"],aliases:["Pattern","LVal"],fields:{properties:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("RestProperty","Property")))}}}),n["default"]("SpreadElement",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:r.assertNodeType("Expression")}}}),n["default"]("Super",{aliases:["Expression"]}),n["default"]("TaggedTemplateExpression",{visitor:["tag","quasi"],aliases:["Expression"],fields:{tag:{validate:r.assertNodeType("Expression")},quasi:{validate:r.assertNodeType("TemplateLiteral")}}}),n["default"]("TemplateElement",{builder:["value","tail"],fields:{value:{},tail:{validate:r.assertValueType("boolean"),"default":!1}}}),n["default"]("TemplateLiteral",{visitor:["quasis","expressions"],aliases:["Expression","Literal"],fields:{quasis:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("TemplateElement")))},expressions:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("Expression")))}}}),n["default"]("YieldExpression",{builder:["argument","delegate"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{delegate:{validate:r.assertValueType("boolean"),"default":!1},argument:{optional:!0,validate:r.assertNodeType("Expression")}}})},function(t,e,s){"use strict";var i=s(85)["default"],r=s(169),n=i(r);n["default"]("AnyTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),n["default"]("ArrayTypeAnnotation",{visitor:["elementType"],aliases:["Flow"],fields:{}}),n["default"]("BooleanTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),n["default"]("BooleanLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),n["default"]("NullLiteralTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),n["default"]("ClassImplements",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),n["default"]("ClassProperty",{visitor:["key","value","typeAnnotation","decorators"],aliases:["Flow","Property"],fields:{}}),n["default"]("DeclareClass",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("DeclareFunction",{visitor:["id"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("DeclareInterface",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("DeclareModule",{visitor:["id","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("DeclareTypeAlias",{visitor:["id","typeParameters","right"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("DeclareVariable",{visitor:["id"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("ExistentialTypeParam",{aliases:["Flow"]}),n["default"]("FunctionTypeAnnotation",{visitor:["typeParameters","params","rest","returnType"],aliases:["Flow"],fields:{}}),n["default"]("FunctionTypeParam",{visitor:["name","typeAnnotation"],aliases:["Flow"],fields:{}}),n["default"]("GenericTypeAnnotation",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),n["default"]("InterfaceExtends",{visitor:["id","typeParameters"],aliases:["Flow"], fields:{}}),n["default"]("InterfaceDeclaration",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("IntersectionTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),n["default"]("MixedTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"]}),n["default"]("NullableTypeAnnotation",{visitor:["typeAnnotation"],aliases:["Flow"],fields:{}}),n["default"]("NumericLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),n["default"]("NumberTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),n["default"]("StringLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),n["default"]("StringTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),n["default"]("ThisTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),n["default"]("TupleTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),n["default"]("TypeofTypeAnnotation",{visitor:["argument"],aliases:["Flow"],fields:{}}),n["default"]("TypeAlias",{visitor:["id","typeParameters","right"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),n["default"]("TypeAnnotation",{visitor:["typeAnnotation"],aliases:["Flow"],fields:{}}),n["default"]("TypeCastExpression",{visitor:["expression","typeAnnotation"],aliases:["Flow","ExpressionWrapper","Expression"],fields:{}}),n["default"]("TypeParameterDeclaration",{visitor:["params"],aliases:["Flow"],fields:{}}),n["default"]("TypeParameterInstantiation",{visitor:["params"],aliases:["Flow"],fields:{}}),n["default"]("ObjectTypeAnnotation",{visitor:["properties","indexers","callProperties"],aliases:["Flow"],fields:{}}),n["default"]("ObjectTypeCallProperty",{visitor:["value"],aliases:["Flow","UserWhitespacable"],fields:{}}),n["default"]("ObjectTypeIndexer",{visitor:["id","key","value"],aliases:["Flow","UserWhitespacable"],fields:{}}),n["default"]("ObjectTypeProperty",{visitor:["key","value"],aliases:["Flow","UserWhitespacable"],fields:{}}),n["default"]("QualifiedTypeIdentifier",{visitor:["id","qualification"],aliases:["Flow"],fields:{}}),n["default"]("UnionTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),n["default"]("VoidTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}})},function(t,e,s){"use strict";var i=s(85)["default"],r=s(169),n=i(r);n["default"]("JSXAttribute",{visitor:["name","value"],aliases:["JSX","Immutable"],fields:{name:{validate:r.assertNodeType("JSXIdentifier","JSXNamespacedName")},value:{optional:!0,validate:r.assertNodeType("JSXElement","StringLiteral","JSXExpressionContainer")}}}),n["default"]("JSXClosingElement",{visitor:["name"],aliases:["JSX","Immutable"],fields:{name:{validate:r.assertNodeType("JSXIdentifier","JSXMemberExpression")}}}),n["default"]("JSXElement",{builder:["openingElement","closingElement","children","selfClosing"],visitor:["openingElement","children","closingElement"],aliases:["JSX","Immutable","Expression"],fields:{openingElement:{validate:r.assertNodeType("JSXOpeningElement")},closingElement:{optional:!0,validate:r.assertNodeType("JSXClosingElement")},children:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("JSXText","JSXExpressionContainer","JSXElement")))}}}),n["default"]("JSXEmptyExpression",{aliases:["JSX","Expression"]}),n["default"]("JSXExpressionContainer",{visitor:["expression"],aliases:["JSX","Immutable"],fields:{expression:{validate:r.assertNodeType("Expression")}}}),n["default"]("JSXIdentifier",{builder:["name"],aliases:["JSX","Expression"],fields:{name:{validate:r.assertValueType("string")}}}),n["default"]("JSXMemberExpression",{visitor:["object","property"],aliases:["JSX","Expression"],fields:{object:{validate:r.assertNodeType("JSXMemberExpression","JSXIdentifier")},property:{validate:r.assertNodeType("JSXIdentifier")}}}),n["default"]("JSXNamespacedName",{visitor:["namespace","name"],aliases:["JSX"],fields:{namespace:{validate:r.assertNodeType("JSXIdentifier")},name:{validate:r.assertNodeType("JSXIdentifier")}}}),n["default"]("JSXOpeningElement",{builder:["name","attributes","selfClosing"],visitor:["name","attributes"],aliases:["JSX","Immutable"],fields:{name:{validate:r.assertNodeType("JSXIdentifier","JSXMemberExpression")},selfClosing:{"default":!1,validate:r.assertValueType("boolean")},attributes:{validate:r.chain(r.assertValueType("array"),r.assertEach(r.assertNodeType("JSXAttribute","JSXSpreadAttribute")))}}}),n["default"]("JSXSpreadAttribute",{visitor:["argument"],aliases:["JSX"],fields:{argument:{validate:r.assertNodeType("Expression")}}}),n["default"]("JSXText",{aliases:["JSX"],builder:["value"],fields:{value:{validate:r.assertValueType("string")}}})},function(t,e,s){"use strict";var i=s(85)["default"],r=s(169),n=i(r);n["default"]("Noop",{visitor:[]}),n["default"]("ParenthesizedExpression",{visitor:["expression"],aliases:["Expression","ExpressionWrapper"],fields:{expression:{validate:r.assertNodeType("Expression")}}})},function(t,e,s){"use strict";var i=s(85)["default"],r=s(169),n=i(r);n["default"]("AwaitExpression",{builder:["argument"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{argument:{validate:r.assertNodeType("Expression")}}}),n["default"]("BindExpression",{visitor:["object","callee"],aliases:["Expression"],fields:{}}),n["default"]("Decorator",{visitor:["expression"],fields:{expression:{validate:r.assertNodeType("Expression")}}}),n["default"]("DoExpression",{visitor:["body"],aliases:["Expression"],fields:{body:{validate:r.assertNodeType("BlockStatement")}}}),n["default"]("ExportDefaultSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:r.assertNodeType("Identifier")}}}),n["default"]("ExportNamespaceSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:r.assertNodeType("Identifier")}}}),n["default"]("RestProperty",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:r.assertNodeType("LVal")}}}),n["default"]("SpreadProperty",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:r.assertNodeType("Expression")}}})},function(t,e,s){"use strict";function i(t){return!!t&&/^[a-z]|\-/.test(t)}function r(t,e){for(var s=t.value.split(/\r\n|\n|\r/),i=0,r=0;r<s.length;r++)s[r].match(/[^ \t]/)&&(i=r);for(var n="",r=0;r<s.length;r++){var a=s[r],o=0===r,p=r===s.length-1,c=r===i,l=a.replace(/\t/g," ");o||(l=l.replace(/^[ ]+/,"")),p||(l=l.replace(/[ ]+$/,"")),l&&(c||(l+=" "),n+=l)}n&&e.push(u.stringLiteral(n))}function n(t){for(var e=[],s=0;s<t.children.length;s++){var i=t.children[s];u.isJSXText(i)?r(i,e):(u.isJSXExpressionContainer(i)&&(i=i.expression),u.isJSXEmptyExpression(i)||e.push(i))}return e}var a=s(86)["default"];e.__esModule=!0,e.isCompatTag=i,e.buildChildren=n;var o=s(41),u=a(o),p=u.buildMatchMemberExpression("React.Component");e.isReactComponent=p},function(t,e,s){"use strict";function i(t,e,s){for(var i=[].concat(t),r=n(null);i.length;){var a=i.shift();if(a){var o=u.getBindingIdentifiers.keys[a.type];if(u.isIdentifier(a))if(e){var p=r[a.name]=r[a.name]||[];p.push(a)}else r[a.name]=a;else if(u.isExportDeclaration(a))u.isDeclaration(t.declaration)&&i.push(t.declaration);else{if(s){if(u.isFunctionDeclaration(a)){i.push(a.id);continue}if(u.isFunctionExpression(a))continue}if(o)for(var c=0;c<o.length;c++){var l=o[c];a[l]&&(i=i.concat(a[l]))}}}}return r}function r(t,e){return i(t,e,!0)}var n=s(185)["default"],a=s(86)["default"];e.__esModule=!0,e.getBindingIdentifiers=i,e.getOuterBindingIdentifiers=r;var o=s(41),u=a(o);i.keys={DeclareClass:["id"],DeclareFunction:["id"],DeclareModule:["id"],DeclareVariable:["id"],InterfaceDeclaration:["id"],TypeAlias:["id"],CatchClause:["param"],LabeledStatement:["label"],UnaryExpression:["argument"],AssignmentExpression:["left"],ImportSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportDefaultSpecifier:["local"],ImportDeclaration:["specifiers"],ExportSpecifier:["exported"],ExportNamespaceSpecifier:["exported"],ExportDefaultSpecifier:["exported"],FunctionDeclaration:["id","params"],FunctionExpression:["id","params"],ClassDeclaration:["id"],ClassExpression:["id"],RestElement:["argument"],UpdateExpression:["argument"],SpreadProperty:["argument"],ObjectProperty:["value"],AssignmentPattern:["left"],ArrayPattern:["elements"],ObjectPattern:["properties"],VariableDeclaration:["declarations"],VariableDeclarator:["id"]}},function(t,e,s){t.exports={"default":s(186),__esModule:!0}},function(t,e,s){var i=s(68);t.exports=function(t,e){return i.create(t,e)}},function(t,e,s){"use strict";function i(t,e){var s=y.getBindingIdentifiers.keys[e.type];if(s)for(var i=0;i<s.length;i++){var r=s[i],n=e[r];if(Array.isArray(n)){if(n.indexOf(t)>=0)return!0}else if(n===t)return!0}return!1}function r(t,e){switch(e.type){case"MemberExpression":case"JSXMemberExpression":case"BindExpression":return e.property===t&&e.computed?!0:e.object===t?!0:!1;case"MetaProperty":return!1;case"ObjectProperty":if(e.key===t)return e.computed;case"VariableDeclarator":return e.id!==t;case"ArrowFunctionExpression":case"FunctionDeclaration":case"FunctionExpression":for(var s=e.params,i=Array.isArray(s),r=0,s=i?s:h(s);;){var n;if(i){if(r>=s.length)break;n=s[r++]}else{if(r=s.next(),r.done)break;n=r.value}var a=n;if(a===t)return!1}return e.id!==t;case"ExportSpecifier":return e.source?!1:e.local===t;case"ExportNamespaceSpecifier":case"ExportDefaultSpecifier":return!1;case"JSXAttribute":return e.name!==t;case"ClassProperty":return e.value===t;case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ImportSpecifier":return!1;case"ClassDeclaration":case"ClassExpression":return e.id!==t;case"ClassMethod":case"ObjectMethod":return e.key===t&&e.computed;case"LabeledStatement":return!1;case"CatchClause":return e.param!==t;case"RestElement":return!1;case"AssignmentExpression":return e.right===t;case"AssignmentPattern":return e.right===t;case"ObjectPattern":case"ArrayPattern":return!1}return!0}function n(t){return"string"!=typeof t||v["default"].keyword.isReservedWordES6(t,!0)?!1:v["default"].keyword.isIdentifierNameES6(t)}function a(t){return x.isVariableDeclaration(t)&&("var"!==t.kind||t[A.BLOCK_SCOPED_SYMBOL])}function o(t){return x.isFunctionDeclaration(t)||x.isClassDeclaration(t)||x.isLet(t)}function u(t){return x.isVariableDeclaration(t,{kind:"var"})&&!t[A.BLOCK_SCOPED_SYMBOL]}function p(t){return x.isImportDefaultSpecifier(t)||x.isIdentifier(t.imported||t.exported,{name:"default"})}function c(t,e){return x.isBlockStatement(t)&&x.isFunction(e,{body:t})?!1:x.isScopable(t)}function l(t){return x.isType(t.type,"Immutable")?!0:x.isIdentifier(t)&&"undefined"===t.name?!0:!1}var h=s(54)["default"],f=s(85)["default"],d=s(86)["default"];e.__esModule=!0,e.isBinding=i,e.isReferenced=r,e.isValidIdentifier=n,e.isLet=a,e.isBlockScoped=o,e.isVar=u,e.isSpecifierDefault=p,e.isScope=c,e.isImmutable=l;var y=s(184),m=s(188),v=f(m),g=s(41),x=d(g),A=s(171)},function(t,e,s){!function(){"use strict";e.ast=s(189),e.code=s(190),e.keyword=s(191)}()},function(t,e){!function(){"use strict";function e(t){if(null==t)return!1;switch(t.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return!0}return!1}function s(t){if(null==t)return!1;switch(t.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return!0}return!1}function i(t){if(null==t)return!1;switch(t.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return!0}return!1}function r(t){return i(t)||null!=t&&"FunctionDeclaration"===t.type}function n(t){switch(t.type){case"IfStatement":return null!=t.alternate?t.alternate:t.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return t.body}return null}function a(t){var e;if("IfStatement"!==t.type)return!1;if(null==t.alternate)return!1;e=t.consequent;do{if("IfStatement"===e.type&&null==e.alternate)return!0;e=n(e)}while(e);return!1}t.exports={isExpression:e,isStatement:i,isIterationStatement:s,isSourceElement:r,isProblematicIfStatement:a,trailingStatement:n}}()},function(t,e){!function(){"use strict";function e(t){return t>=48&&57>=t}function s(t){return t>=48&&57>=t||t>=97&&102>=t||t>=65&&70>=t}function i(t){return t>=48&&55>=t}function r(t){return 32===t||9===t||11===t||12===t||160===t||t>=5760&&f.indexOf(t)>=0}function n(t){return 10===t||13===t||8232===t||8233===t}function a(t){if(65535>=t)return String.fromCharCode(t);var e=String.fromCharCode(Math.floor((t-65536)/1024)+55296),s=String.fromCharCode((t-65536)%1024+56320);return e+s}function o(t){return 128>t?d[t]:h.NonAsciiIdentifierStart.test(a(t))}function u(t){return 128>t?y[t]:h.NonAsciiIdentifierPart.test(a(t))}function p(t){return 128>t?d[t]:l.NonAsciiIdentifierStart.test(a(t))}function c(t){return 128>t?y[t]:l.NonAsciiIdentifierPart.test(a(t))}var l,h,f,d,y,m;for(h={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,NonAsciiIdentifierPart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/},l={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ },f=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],d=new Array(128),m=0;128>m;++m)d[m]=m>=97&&122>=m||m>=65&&90>=m||36===m||95===m;for(y=new Array(128),m=0;128>m;++m)y[m]=m>=97&&122>=m||m>=65&&90>=m||m>=48&&57>=m||36===m||95===m;t.exports={isDecimalDigit:e,isHexDigit:s,isOctalDigit:i,isWhiteSpace:r,isLineTerminator:n,isIdentifierStartES5:o,isIdentifierPartES5:u,isIdentifierStartES6:p,isIdentifierPartES6:c}}()},function(t,e,s){!function(){"use strict";function e(t){switch(t){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return!0;default:return!1}}function i(t,e){return e||"yield"!==t?r(t,e):!1}function r(t,s){if(s&&e(t))return!0;switch(t.length){case 2:return"if"===t||"in"===t||"do"===t;case 3:return"var"===t||"for"===t||"new"===t||"try"===t;case 4:return"this"===t||"else"===t||"case"===t||"void"===t||"with"===t||"enum"===t;case 5:return"while"===t||"break"===t||"catch"===t||"throw"===t||"const"===t||"yield"===t||"class"===t||"super"===t;case 6:return"return"===t||"typeof"===t||"delete"===t||"switch"===t||"export"===t||"import"===t;case 7:return"default"===t||"finally"===t||"extends"===t;case 8:return"function"===t||"continue"===t||"debugger"===t;case 10:return"instanceof"===t;default:return!1}}function n(t,e){return"null"===t||"true"===t||"false"===t||i(t,e)}function a(t,e){return"null"===t||"true"===t||"false"===t||r(t,e)}function o(t){return"eval"===t||"arguments"===t}function u(t){var e,s,i;if(0===t.length)return!1;if(i=t.charCodeAt(0),!f.isIdentifierStartES5(i))return!1;for(e=1,s=t.length;s>e;++e)if(i=t.charCodeAt(e),!f.isIdentifierPartES5(i))return!1;return!0}function p(t,e){return 1024*(t-55296)+(e-56320)+65536}function c(t){var e,s,i,r,n;if(0===t.length)return!1;for(n=f.isIdentifierStartES6,e=0,s=t.length;s>e;++e){if(i=t.charCodeAt(e),i>=55296&&56319>=i){if(++e,e>=s)return!1;if(r=t.charCodeAt(e),!(r>=56320&&57343>=r))return!1;i=p(i,r)}if(!n(i))return!1;n=f.isIdentifierPartES6}return!0}function l(t,e){return u(t)&&!n(t,e)}function h(t,e){return c(t)&&!a(t,e)}var f=s(190);t.exports={isKeywordES5:i,isKeywordES6:r,isReservedWordES5:n,isReservedWordES6:a,isRestrictedWord:o,isIdentifierNameES5:u,isIdentifierNameES6:c,isIdentifierES5:l,isIdentifierES6:h}}()},function(t,e,s){"use strict";function i(t){var e=arguments.length<=1||void 0===arguments[1]?t.key||t.property:arguments[1];return function(){return t.computed||w.isIdentifier(e)&&(e=w.stringLiteral(e.name)),e}()}function r(t,e){function s(t){for(var n=!1,a=[],o=t,u=Array.isArray(o),p=0,o=u?o:h(o);;){var c;if(u){if(p>=o.length)break;c=o[p++]}else{if(p=o.next(),p.done)break;c=p.value}var l=c;if(w.isExpression(l))a.push(l);else if(w.isExpressionStatement(l))a.push(l.expression);else{if(w.isVariableDeclaration(l)){if("var"!==l.kind)return r=!0;for(var f=l.declarations,d=Array.isArray(f),y=0,f=d?f:h(f);;){var m;if(d){if(y>=f.length)break;m=f[y++]}else{if(y=f.next(),y.done)break;m=y.value}var v=m,g=w.getBindingIdentifiers(v);for(var x in g)i.push({kind:l.kind,id:g[x]});v.init&&a.push(w.assignmentExpression("=",v.id,v.init))}n=!0;continue}if(w.isIfStatement(l)){var A=l.consequent?s([l.consequent]):e.buildUndefinedNode(),b=l.alternate?s([l.alternate]):e.buildUndefinedNode();if(!A||!b)return r=!0;a.push(w.conditionalExpression(l.test,A,b))}else{if(!w.isBlockStatement(l)){if(w.isEmptyStatement(l)){n=!0;continue}return r=!0}a.push(s(l.body))}}n=!1}return(n||0===a.length)&&a.push(e.buildUndefinedNode()),1===a.length?a[0]:w.sequenceExpression(a)}if(t&&t.length){var i=[],r=!1,n=s(t);if(!r){for(var a=0;a<i.length;a++)e.push(i[a]);return n}}}function n(t){var e=arguments.length<=1||void 0===arguments[1]?t.key:arguments[1];return function(){var s=void 0;return"method"===t.kind?n.increment()+"":(s=w.isIdentifier(e)?e.name:w.isStringLiteral(e)?JSON.stringify(e.value):JSON.stringify(S["default"].removeProperties(w.cloneDeep(e))),t.computed&&(s="["+s+"]"),t["static"]&&(s="static:"+s),s)}()}function a(t){return t+="",t=t.replace(/[^a-zA-Z0-9$_]/g,"-"),t=t.replace(/^[-0-9]+/,""),t=t.replace(/[-\s]+(.)?/g,function(t,e){return e?e.toUpperCase():""}),w.isValidIdentifier(t)||(t="_"+t),t||"_"}function o(t){return t=a(t),("eval"===t||"arguments"===t)&&(t="_"+t),t}function u(t,e){if(w.isStatement(t))return t;var s=!1,i=void 0;if(w.isClass(t))s=!0,i="ClassDeclaration";else if(w.isFunction(t))s=!0,i="FunctionDeclaration";else if(w.isAssignmentExpression(t))return w.expressionStatement(t);if(s&&!t.id&&(i=!1),!i){if(e)return!1;throw new Error("cannot turn "+t.type+" to a statement")}return t.type=i,t}function p(t){if(w.isExpressionStatement(t)&&(t=t.expression),w.isClass(t)?t.type="ClassExpression":w.isFunction(t)&&(t.type="FunctionExpression"),w.isExpression(t))return t;throw new Error("cannot turn "+t.type+" to an expression")}function c(t,e){return w.isBlockStatement(t)?t:(w.isEmptyStatement(t)&&(t=[]),Array.isArray(t)||(w.isStatement(t)||(t=w.isFunction(e)?w.returnStatement(t):w.expressionStatement(t)),t=[t]),w.blockStatement(t))}function l(t){if(void 0===t)return w.identifier("undefined");if(t===!0||t===!1)return w.booleanLiteral(t);if(null===t)return w.nullLiteral();if(C["default"](t))return w.stringLiteral(t);if(x["default"](t))return w.numericLiteral(t);if(b["default"](t)){var e=t.source,s=t.toString().match(/\/([a-z]+|)$/)[1];return w.regExpLiteral(e,s)}if(Array.isArray(t))return w.arrayExpression(t.map(w.valueToNode));if(v["default"](t)){var i=[];for(var r in t){var n=void 0;n=w.isValidIdentifier(r)?w.identifier(r):w.stringLiteral(r),i.push(w.objectProperty(n,w.valueToNode(t[r])))}return w.objectExpression(i)}throw new Error("don't know how to turn this value into a node")}var h=s(54)["default"],f=s(193)["default"],d=s(85)["default"],y=s(86)["default"];e.__esModule=!0,e.toComputedKey=i,e.toSequenceExpression=r,e.toKeyAlias=n,e.toIdentifier=a,e.toBindingIdentifierName=o,e.toStatement=u,e.toExpression=p,e.toBlock=c,e.valueToNode=l;var m=s(196),v=d(m),g=s(198),x=d(g),A=s(199),b=d(A),E=s(200),C=d(E),D=s(201),S=d(D),F=s(41),w=y(F);n.uid=0,n.increment=function(){return n.uid>=f?n.uid=0:n.uid++}},function(t,e,s){t.exports={"default":s(194),__esModule:!0}},function(t,e,s){s(195),t.exports=9007199254740991},function(t,e,s){var i=s(48);i(i.S,"Number",{MAX_SAFE_INTEGER:9007199254740991})},function(t,e,s){function i(t){var e;if(!a(t)||c.call(t)!=o||n(t)||!p.call(t,"constructor")&&(e=t.constructor,"function"==typeof e&&!(e instanceof e)))return!1;var s;return r(t,function(t,e){s=e}),void 0===s||p.call(t,s)}var r=s(197),n=s(117),a=s(111),o="[object Object]",u=Object.prototype,p=u.hasOwnProperty,c=u.toString;t.exports=i},function(t,e,s){function i(t,e){return r(t,e,n)}var r=s(122),n=s(120);t.exports=i},function(t,e,s){function i(t){return"number"==typeof t||r(t)&&o.call(t)==n}var r=s(111),n="[object Number]",a=Object.prototype,o=a.toString;t.exports=i},function(t,e,s){function i(t){return r(t)&&o.call(t)==n}var r=s(110),n="[object RegExp]",a=Object.prototype,o=a.toString;t.exports=i},function(t,e,s){function i(t){return"string"==typeof t||r(t)&&o.call(t)==n}var r=s(111),n="[object String]",a=Object.prototype,o=a.toString;t.exports=i},function(t,e,s){"use strict";function i(t,e,s,r,n){if(t){if(e||(e={}),!e.noScope&&!s&&"Program"!==t.type&&"File"!==t.type)throw new Error(y.get("traverseNeedsParent",t.type));f.explode(e),i.node(t,e,s,r,n)}}function r(t,e){t.node.type===e.type&&(e.has=!0,t.skip())}var n=s(54)["default"],a=s(202)["default"],o=s(85)["default"],u=s(86)["default"],p=s(204)["default"];e.__esModule=!0,e["default"]=i;var c=s(205),l=o(c),h=s(269),f=u(h),d=s(234),y=u(d),m=s(223),v=o(m),g=s(41),x=u(g),A=s(208);e.NodePath=p(A);var b=s(219);e.Scope=p(b);var E=s(270);e.Hub=p(E),e.visitors=f,i.visitors=f,i.verify=f.verify,i.explode=f.explode,i.NodePath=s(208),i.Scope=s(219),i.Hub=s(270),i.cheap=function(t,e){if(t){var s=x.VISITOR_KEYS[t.type];if(s){e(t);for(var r=s,a=Array.isArray(r),o=0,r=a?r:n(r);;){var u;if(a){if(o>=r.length)break;u=r[o++]}else{if(o=r.next(),o.done)break;u=o.value}var p=u,c=t[p];if(Array.isArray(c))for(var l=c,h=Array.isArray(l),f=0,l=h?l:n(l);;){var d;if(h){if(f>=l.length)break;d=l[f++]}else{if(f=l.next(),f.done)break;d=f.value}var y=d;i.cheap(y,e)}else i.cheap(c,e)}}}},i.node=function(t,e,s,i,r,a){var o=x.VISITOR_KEYS[t.type];if(o)for(var u=new l["default"](s,e,i,r),p=o,c=Array.isArray(p),h=0,p=c?p:n(p);;){var f;if(c){if(h>=p.length)break;f=p[h++]}else{if(h=p.next(),h.done)break;f=h.value}var d=f;if((!a||!a[d])&&u.visit(t,d))return}};var C=x.COMMENT_KEYS.concat(["tokens","comments","start","end","loc","raw","rawValue"]);i.clearNode=function(t){for(var e=C,s=Array.isArray(e),i=0,e=s?e:n(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var o=r;null!=t[o]&&(t[o]=void 0)}for(var o in t)"_"===o[0]&&null!=t[o]&&(t[o]=void 0);for(var u=a(t),p=u,c=Array.isArray(p),l=0,p=c?p:n(p);;){var h;if(c){if(l>=p.length)break;h=p[l++]}else{if(l=p.next(),l.done)break;h=l.value}var f=h;t[f]=null}},i.removeProperties=function(t){return i.cheap(t,i.clearNode),t},i.hasType=function(t,e,s,n){if(v["default"](n,t.type))return!1;if(t.type===s)return!0;var a={has:!1,type:s};return i(t,{blacklist:n,enter:r},e,a),a.has}},function(t,e,s){t.exports={"default":s(203),__esModule:!0}},function(t,e,s){s(174),t.exports=s(50).Object.getOwnPropertySymbols},function(t,e){"use strict";e["default"]=function(t){return t&&t.__esModule?t["default"]:t},e.__esModule=!0},function(t,e,s){(function(i){"use strict";var r=s(207)["default"],n=s(54)["default"],a=s(85)["default"],o=s(86)["default"];e.__esModule=!0;var u=s(208),p=a(u),c=s(41),l=o(c),h="test"===i.env.NODE_ENV,f=function(){function t(e,s,i,n){r(this,t),this.parentPath=n,this.scope=e,this.state=i,this.opts=s}return t.prototype.shouldVisit=function(t){var e=this.opts;if(e.enter||e.exit)return!0;if(e[t.type])return!0;var s=l.VISITOR_KEYS[t.type];if(!s||!s.length)return!1;for(var i=s,r=Array.isArray(i),a=0,i=r?i:n(i);;){var o;if(r){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;if(t[u])return!0}return!1},t.prototype.create=function(t,e,s,i){return p["default"].get({parentPath:this.parentPath,parent:t,container:e,key:s,listKey:i})},t.prototype.maybeQueue=function(t,e){if(this.trap)throw new Error("Infinite cycle detected");this.queue&&(e?this.queue.push(t):this.priorityQueue.push(t))},t.prototype.visitMultiple=function(t,e,s){if(0===t.length)return!1;for(var i=[],r=0;r<t.length;r++){var n=t[r];n&&this.shouldVisit(n)&&i.push(this.create(e,t,r,s))}return this.visitQueue(i)},t.prototype.visitSingle=function(t,e){return this.shouldVisit(t[e])?this.visitQueue([this.create(t,t,e)]):!1},t.prototype.visitQueue=function(t){this.queue=t,this.priorityQueue=[];for(var e=[],s=!1,i=t,r=Array.isArray(i),a=0,i=r?i:n(i);;){var o;if(r){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;if(u.resync(),u.pushContext(this),h&&t.length>=1e3&&(this.trap=!0),!(e.indexOf(u.node)>=0)){if(e.push(u.node),u.visit()){s=!0;break}if(this.priorityQueue.length&&(s=this.visitQueue(this.priorityQueue),this.priorityQueue=[],this.queue=t,s))break}}for(var p=t,c=Array.isArray(p),l=0,p=c?p:n(p);;){var f;if(c){if(l>=p.length)break;f=p[l++]}else{if(l=p.next(),l.done)break;f=l.value}var u=f;u.popContext()}return this.queue=null,s},t.prototype.visit=function(t,e){var s=t[e];return s?Array.isArray(s)?this.visitMultiple(s,t,e):this.visitSingle(t,e):!1},t}();e["default"]=f,t.exports=e["default"]}).call(e,s(206))},function(t,e){function s(){p=!1,a.length?u=a.concat(u):c=-1,u.length&&i()}function i(){if(!p){var t=setTimeout(s);p=!0;for(var e=u.length;e;){for(a=u,u=[];++c<e;)a&&a[c].run();c=-1,e=u.length}a=null,p=!1,clearTimeout(t)}}function r(t,e){this.fun=t,this.array=e}function n(){}var a,o=t.exports={},u=[],p=!1,c=-1;o.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var s=1;s<arguments.length;s++)e[s-1]=arguments[s];u.push(new r(t,e)),1!==u.length||p||setTimeout(i,0)},r.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=n,o.addListener=n,o.once=n,o.off=n,o.removeListener=n,o.removeAllListeners=n,o.emit=n,o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(t,e){"use strict";e["default"]=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},e.__esModule=!0},function(t,e,s){"use strict";var i=s(207)["default"],r=s(54)["default"],n=s(86)["default"],a=s(85)["default"];e.__esModule=!0;var o=s(209),u=n(o),p=s(210),c=a(p),l=s(213),h=s(214),f=a(h),d=s(201),y=a(d),m=s(215),v=a(m),g=s(219),x=a(g),A=s(41),b=n(A),E=c["default"]("babel"),C=function(){function t(e,s){i(this,t),this.parent=s,this.hub=e,this.contexts=[],this.data={},this.shouldSkip=!1,this.shouldStop=!1,this.removed=!1,this.state=null,this.opts=null,this.skipKeys=null,this.parentPath=null,this.context=null,this.container=null,this.listKey=null,this.inList=!1,this.parentKey=null,this.key=null,this.node=null,this.scope=null,this.type=null,this.typeAnnotation=null}return t.get=function(e){var s=e.hub,i=e.parentPath,r=e.parent,n=e.container,a=e.listKey,o=e.key;!s&&i&&(s=i.hub),f["default"](r,"To get a node path the parent needs to exist");for(var u=n[o],p=r[l.PATH_CACHE_KEY]=r[l.PATH_CACHE_KEY]||[],c=void 0,h=0;h<p.length;h++){var d=p[h];if(d.node===u){c=d;break}}if(c&&!(c instanceof t)){if("NodePath"!==c.constructor.name)throw new Error("We found a path that isn't a NodePath instance. Possiblly due to bad serialisation.");c=null}return c||(c=new t(s,r),p.push(c)),c.setup(i,n,a,o),c},t.prototype.getScope=function(t){var e=t;return this.isScope()&&(e=new x["default"](this,t)),e},t.prototype.setData=function(t,e){return this.data[t]=e},t.prototype.getData=function(t,e){var s=this.data[t];return!s&&e&&(s=this.data[t]=e),s},t.prototype.buildCodeFrameError=function(t){var e=arguments.length<=1||void 0===arguments[1]?SyntaxError:arguments[1];return this.hub.file.buildCodeFrameError(this.node,t,e)},t.prototype.traverse=function(t,e){y["default"](this.node,t,this.scope,e,this)},t.prototype.mark=function(t,e){this.hub.file.metadata.marked.push({type:t,message:e,loc:this.node.loc})},t.prototype.set=function(t,e){b.validate(this.node,t,e),this.node[t]=e},t.prototype.getPathLocation=function(){var t=[],e=this;do{var s=e.key;e.inList&&(s=e.listKey+"["+s+"]"),t.unshift(s)}while(e=e.parentPath);return t.join(".")},t.prototype.debug=function(t){E.enabled&&E(this.getPathLocation()+" "+this.type+": "+t())},t}();e["default"]=C,v["default"](C.prototype,s(240)),v["default"](C.prototype,s(241)),v["default"](C.prototype,s(244)),v["default"](C.prototype,s(259)),v["default"](C.prototype,s(260)),v["default"](C.prototype,s(261)),v["default"](C.prototype,s(262)),v["default"](C.prototype,s(263)),v["default"](C.prototype,s(265)),v["default"](C.prototype,s(267)),v["default"](C.prototype,s(268));for(var D=function(){if(F){if(w>=S.length)return"break";T=S[w++]}else{if(w=S.next(),w.done)return"break";T=w.value}var t=T,e="is"+t;C.prototype[e]=function(t){return b[e](this.node,t)},C.prototype["assert"+t]=function(s){if(!this[e](s))throw new TypeError("Expected node path of type "+t)}},S=b.TYPES,F=Array.isArray(S),w=0,S=F?S:r(S);;){var T,k=D();if("break"===k)break}var P=function(t){if("_"===t[0])return"continue";b.TYPES.indexOf(t)<0&&b.TYPES.push(t);var e=u[t];C.prototype["is"+t]=function(t){return e.checkPath(this,t)}};for(var _ in u){P(_)}t.exports=e["default"]},function(t,e,s){"use strict";var i=s(86)["default"];e.__esModule=!0;var r=s(41),n=i(r),a={types:["Identifier","JSXIdentifier"],checkPath:function(t,e){var s=t.node,i=t.parent;if(!n.isIdentifier(s,e)){if(!n.isJSXIdentifier(s,e))return!1;if(r.react.isCompatTag(s.name))return!1}return n.isReferenced(s,i)}};e.ReferencedIdentifier=a;var o={types:["MemberExpression"],checkPath:function(t){var e=t.node,s=t.parent;return n.isMemberExpression(e)&&n.isReferenced(e,s)}};e.ReferencedMemberExpression=o;var u={types:["Identifier"],checkPath:function(t){var e=t.node,s=t.parent;return n.isIdentifier(e)&&n.isBinding(e,s)}};e.BindingIdentifier=u;var p={types:["Statement"],checkPath:function(t){var e=t.node,s=t.parent;if(n.isStatement(e)){if(n.isVariableDeclaration(e)){if(n.isForXStatement(s,{left:e}))return!1;if(n.isForStatement(s,{init:e}))return!1}return!0}return!1}};e.Statement=p;var c={types:["Expression"],checkPath:function(t){return t.isIdentifier()?t.isReferencedIdentifier():n.isExpression(t.node)}};e.Expression=c;var l={types:["Scopable"],checkPath:function(t){return n.isScope(t.node,t.parent)}};e.Scope=l;var h={checkPath:function(t){return n.isReferenced(t.node,t.parent)}};e.Referenced=h;var f={checkPath:function(t){return n.isBlockScoped(t.node)}};e.BlockScoped=f;var d={types:["VariableDeclaration"],checkPath:function(t){return n.isVar(t.node)}};e.Var=d;var y={checkPath:function(t){return t.node&&!!t.node.loc}};e.User=y;var m={checkPath:function(t){return!t.isUser()}};e.Generated=m;var v={checkPath:function(t,e){return t.scope.isPure(t.node,e)}};e.Pure=v;var g={types:["Flow","ImportDeclaration","ExportDeclaration"],checkPath:function(t){var e=t.node;return n.isFlow(e)?!0:n.isImportDeclaration(e)?"type"===e.importKind||"typeof"===e.importKind:n.isExportDeclaration(e)?"type"===e.exportKind:!1}};e.Flow=g},function(t,e,s){function i(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function r(){var t=arguments,s=this.useColors;if(t[0]=(s?"%c":"")+this.namespace+(s?" %c":" ")+t[0]+(s?"%c ":" ")+"+"+e.humanize(this.diff),!s)return t;var i="color: "+this.color;t=[t[0],i,"color: inherit"].concat(Array.prototype.slice.call(t,1));var r=0,n=0;return t[0].replace(/%[a-z%]/g,function(t){"%%"!==t&&(r++,"%c"===t&&(n=r))}),t.splice(n,0,i),t}function n(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(s){}}function o(){var t;try{t=e.storage.debug}catch(s){}return t}function u(){try{return window.localStorage}catch(t){}}e=t.exports=s(211),e.log=n,e.formatArgs=r,e.save=a,e.load=o,e.useColors=i,e.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),e.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],e.formatters.j=function(t){return JSON.stringify(t)},e.enable(o())},function(t,e,s){function i(){return e.colors[c++%e.colors.length]}function r(t){function s(){}function r(){var t=r,s=+new Date,n=s-(p||s);t.diff=n,t.prev=p,t.curr=s,p=s,null==t.useColors&&(t.useColors=e.useColors()),null==t.color&&t.useColors&&(t.color=i());var a=Array.prototype.slice.call(arguments);a[0]=e.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var o=0;a[0]=a[0].replace(/%([a-z%])/g,function(s,i){if("%%"===s)return s;o++;var r=e.formatters[i];if("function"==typeof r){var n=a[o];s=r.call(t,n),a.splice(o,1),o--}return s}),"function"==typeof e.formatArgs&&(a=e.formatArgs.apply(t,a));var u=r.log||e.log||console.log.bind(console);u.apply(t,a)}s.enabled=!1,r.enabled=!0;var n=e.enabled(t)?r:s;return n.namespace=t,n}function n(t){e.save(t);for(var s=(t||"").split(/[\s,]+/),i=s.length,r=0;i>r;r++)s[r]&&(t=s[r].replace(/\*/g,".*?"),"-"===t[0]?e.skips.push(new RegExp("^"+t.substr(1)+"$")):e.names.push(new RegExp("^"+t+"$")))}function a(){e.enable("")}function o(t){var s,i;for(s=0,i=e.skips.length;i>s;s++)if(e.skips[s].test(t))return!1;for(s=0,i=e.names.length;i>s;s++)if(e.names[s].test(t))return!0;return!1}function u(t){return t instanceof Error?t.stack||t.message:t}e=t.exports=r,e.coerce=u,e.disable=a,e.enable=n,e.enabled=o,e.humanize=s(212),e.names=[],e.skips=[],e.formatters={};var p,c=0},function(t,e){function s(t){if(t=""+t,!(t.length>1e4)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var s=parseFloat(e[1]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return s*c;case"days":case"day":case"d":return s*p;case"hours":case"hour":case"hrs":case"hr":case"h":return s*u;case"minutes":case"minute":case"mins":case"min":case"m":return s*o;case"seconds":case"second":case"secs":case"sec":case"s":return s*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s}}}}function i(t){return t>=p?Math.round(t/p)+"d":t>=u?Math.round(t/u)+"h":t>=o?Math.round(t/o)+"m":t>=a?Math.round(t/a)+"s":t+"ms"}function r(t){return n(t,p,"day")||n(t,u,"hour")||n(t,o,"minute")||n(t,a,"second")||t+" ms"}function n(t,e,s){return e>t?void 0:1.5*e>t?Math.floor(t/e)+" "+s:Math.ceil(t/e)+" "+s+"s"}var a=1e3,o=60*a,u=60*o,p=24*u,c=365.25*p;t.exports=function(t,e){return e=e||{},"string"==typeof t?s(t):e["long"]?r(t):i(t)}},function(t,e){"use strict";e.__esModule=!0;var s="_paths";e.PATH_CACHE_KEY=s},function(t,e,s){(function(e){"use strict";var s=function(t,s,i,r,n,a,o,u){if("production"!==e.env.NODE_ENV&&void 0===s)throw new Error("invariant requires an error message argument");if(!t){var p;if(void 0===s)p=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[i,r,n,a,o,u],l=0;p=new Error(s.replace(/%s/g,function(){return c[l++]})),p.name="Invariant Violation"}throw p.framesToPop=1,p}};t.exports=s}).call(e,s(206))},function(t,e,s){var i=s(216),r=s(104),n=s(217),a=n(function(t,e,s){return s?i(t,e,s):r(t,e)});t.exports=a},function(t,e,s){function i(t,e,s){for(var i=-1,n=r(e),a=n.length;++i<a;){var o=n[i],u=t[o],p=s(u,e[o],o,t,e);(p===p?p===u:u!==u)&&(void 0!==u||o in t)||(t[o]=p)}return t}var r=s(106);t.exports=i},function(t,e,s){function i(t){return a(function(e,s){var i=-1,a=null==e?0:s.length,o=a>2?s[a-2]:void 0,u=a>2?s[2]:void 0,p=a>1?s[a-1]:void 0;for("function"==typeof o?(o=r(o,p,5),a-=2):(o="function"==typeof p?p:void 0,a-=o?1:0),u&&n(s[0],s[1],u)&&(o=3>a?void 0:o,a=1);++i<a;){var c=s[i];c&&t(e,c,o)}return e})}var r=s(129),n=s(131),a=s(218);t.exports=i},function(t,e){function s(t,e){if("function"!=typeof t)throw new TypeError(i);return e=r(void 0===e?t.length-1:+e||0,0),function(){for(var s=arguments,i=-1,n=r(s.length-e,0),a=Array(n);++i<n;)a[i]=s[e+i];switch(e){case 0:return t.call(this,a);case 1:return t.call(this,s[0],a);case 2:return t.call(this,s[0],s[1],a)}var o=Array(e+1);for(i=-1;++i<e;)o[i]=s[i];return o[e]=a,t.apply(this,o)}}var i="Expected a function",r=Math.max;t.exports=s},function(t,e,s){"use strict";function i(t,e,s){var i=t[k];if(i){if(r(i,e))return i}else if(!t[P])return void(t[k]=s);return n(t,e,s,i)}function r(t,e){return t.parent===e?!0:void 0}function n(t,e,s,i){var n=t[P]=t[P]||[];i&&(n.push(i),t[k]=null);for(var a=n,o=Array.isArray(a),p=0,a=o?a:u(a);;){var c;if(o){if(p>=a.length)break;c=a[p++]}else{if(p=a.next(),p.done)break;c=p.value}var l=c;if(r(l,e))return l}n.push(s)}var a=s(207)["default"],o=s(220)["default"],u=s(54)["default"],p=s(185)["default"],c=s(85)["default"],l=s(86)["default"];e.__esModule=!0;var h=s(223),f=c(h),d=s(226),y=c(d),m=s(229),v=c(m),g=s(201),x=c(g),A=s(231),b=c(A),E=s(234),C=l(E),D=s(230),S=c(D),F=s(238),w=(c(F),s(41)),T=l(w),k=o(),P=o(),_={For:function(t){for(var e=T.FOR_INIT_KEYS,s=Array.isArray(e),i=0,e=s?e:u(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var n=r,a=t.get(n);a.isVar()&&t.scope.getFunctionParent().registerBinding("var",a)}},Declaration:function(t){t.isBlockScoped()||t.isExportDeclaration()&&t.get("declaration").isDeclaration()||t.scope.getFunctionParent().registerDeclaration(t)},ReferencedIdentifier:function(t,e){e.references.push(t)},ForXStatement:function(t,e){var s=t.get("left");(s.isPattern()||s.isIdentifier())&&e.constantViolations.push(s)},ExportDeclaration:{exit:function(t){var e=t.node,s=t.scope,i=e.declaration;if(T.isClassDeclaration(i)||T.isFunctionDeclaration(i)){var r=i.id;if(!r)return;var n=s.getBinding(r.name);n&&n.reference()}else if(T.isVariableDeclaration(i))for(var a=i.declarations,o=Array.isArray(a),p=0,a=o?a:u(a);;){var c;if(o){if(p>=a.length)break;c=a[p++]}else{if(p=a.next(),p.done)break;c=p.value}var l=c,h=T.getBindingIdentifiers(l);for(var f in h){var n=s.getBinding(f);n&&n.reference()}}}},LabeledStatement:function(t){t.scope.getProgramParent().addGlobal(t.node),t.scope.getBlockParent().registerDeclaration(t)},AssignmentExpression:function(t,e){e.assignments.push(t)},UpdateExpression:function(t,e){e.constantViolations.push(t.get("argument"))},UnaryExpression:function(t,e){"delete"===t.node.operator&&e.constantViolations.push(t.get("argument"))},BlockScoped:function(t){var e=t.scope;e.path===t&&(e=e.parent),e.getBlockParent().registerDeclaration(t)},ClassDeclaration:function(t){var e=t.node.id;if(e){var s=e.name;t.scope.bindings[s]=t.scope.getBinding(s)}},Block:function(t){for(var e=t.get("body"),s=e,i=Array.isArray(s),r=0,s=i?s:u(s);;){var n;if(i){if(r>=s.length)break;n=s[r++]}else{if(r=s.next(),r.done)break;n=r.value}var a=n;a.isFunctionDeclaration()&&t.scope.getBlockParent().registerDeclaration(a)}}},B=0,N=function(){function t(e,s){if(a(this,t),s&&s.block===e.node)return s;var r=i(e.node,s,this);return r?r:(this.uid=B++,this.parent=s,this.hub=e.hub,this.parentBlock=e.parent,this.block=e.node,void(this.path=e))}return t.prototype.traverse=function(t,e,s){x["default"](t,e,this,s,this.path)},t.prototype.generateDeclaredUidIdentifier=function(){var t=arguments.length<=0||void 0===arguments[0]?"temp":arguments[0],e=this.generateUidIdentifier(t);return this.push({id:e}),e},t.prototype.generateUidIdentifier=function(){var t=arguments.length<=0||void 0===arguments[0]?"temp":arguments[0];return T.identifier(this.generateUid(t))},t.prototype.generateUid=function(){var t=arguments.length<=0||void 0===arguments[0]?"temp":arguments[0];t=T.toIdentifier(t).replace(/^_+/,"").replace(/[0-9]+$/g,"");var e=void 0,s=0;do e=this._generateUid(t,s),s++;while(this.hasBinding(e)||this.hasGlobal(e)||this.hasReference(e));var i=this.getProgramParent();return i.references[e]=!0,i.uids[e]=!0,e},t.prototype._generateUid=function(t,e){var s=t;return e>1&&(s+=e),"_"+s},t.prototype.generateUidIdentifierBasedOnNode=function(t,e){var s=t;T.isAssignmentExpression(t)?s=t.left:T.isVariableDeclarator(t)?s=t.id:(T.isObjectProperty(s)||T.isObjectMethod(s))&&(s=s.key);var i=[],r=function a(t){if(T.isModuleDeclaration(t))if(t.source)a(t.source);else if(t.specifiers&&t.specifiers.length)for(var e=t.specifiers,s=Array.isArray(e),r=0,e=s?e:u(e);;){var n;if(s){if(r>=e.length)break;n=e[r++]}else{if(r=e.next(),r.done)break;n=r.value}var o=n;a(o)}else t.declaration&&a(t.declaration);else if(T.isModuleSpecifier(t))a(t.local);else if(T.isMemberExpression(t))a(t.object),a(t.property);else if(T.isIdentifier(t))i.push(t.name);else if(T.isLiteral(t))i.push(t.value);else if(T.isCallExpression(t))a(t.callee);else if(T.isObjectExpression(t)||T.isObjectPattern(t))for(var p=t.properties,c=Array.isArray(p),l=0,p=c?p:u(p);;){var h;if(c){if(l>=p.length)break;h=p[l++]}else{if(l=p.next(),l.done)break;h=l.value}var f=h;a(f.key||f.argument)}};r(s);var n=i.join("$");return n=n.replace(/^_/,"")||e||"ref",this.generateUidIdentifier(n.slice(0,20))},t.prototype.isStatic=function(t){if(T.isThisExpression(t)||T.isSuper(t))return!0;if(T.isIdentifier(t)){var e=this.getBinding(t.name);return e?e.constant:this.hasBinding(t.name)}return!1},t.prototype.maybeGenerateMemoised=function(t,e){if(this.isStatic(t))return null;var s=this.generateUidIdentifierBasedOnNode(t);return e||this.push({id:s}),s},t.prototype.checkBlockScopedCollisions=function(t,e,s,i){if("param"!==e&&("hoisted"!==e||"let"!==t.kind)){var r=!1;if(r||(r="let"===e||"let"===t.kind||"const"===t.kind||"module"===t.kind),r||(r="param"===t.kind&&("let"===e||"const"===e)),r)throw this.hub.file.buildCodeFrameError(i,C.get("scopeDuplicateDeclaration",s),TypeError)}},t.prototype.rename=function(t,e,s){var i=this.getBinding(t);return i?(e=e||this.generateUidIdentifier(t).name,new v["default"](i,t,e).rename(s)):void 0},t.prototype._renameFromMap=function(t,e,s,i){t[e]&&(t[s]=i,t[e]=null)},t.prototype.dump=function(){var t=y["default"]("-",60);console.log(t);var e=this;do{console.log("#",e.block.type);for(var s in e.bindings){var i=e.bindings[s];console.log(" -",s,{constant:i.constant,references:i.references,violations:i.constantViolations.length,kind:i.kind})}}while(e=e.parent);console.log(t)},t.prototype.toArray=function(t,e){var s=this.hub.file;if(T.isIdentifier(t)){var i=this.getBinding(t.name);if(i&&i.constant&&i.path.isGenericType("Array"))return t}if(T.isArrayExpression(t))return t;if(T.isIdentifier(t,{name:"arguments"}))return T.callExpression(T.memberExpression(T.memberExpression(T.memberExpression(T.identifier("Array"),T.identifier("prototype")),T.identifier("slice")),T.identifier("call")),[t]);var r="toArray",n=[t];return e===!0?r="toConsumableArray":e&&(n.push(T.numericLiteral(e)),r="slicedToArray"),T.callExpression(s.addHelper(r),n)},t.prototype.registerDeclaration=function(t){if(t.isLabeledStatement())this.registerBinding("label",t);else if(t.isFunctionDeclaration())this.registerBinding("hoisted",t.get("id"),t);else if(t.isVariableDeclaration())for(var e=t.get("declarations"),s=e,i=Array.isArray(s),r=0,s=i?s:u(s);;){var n;if(i){if(r>=s.length)break;n=s[r++]}else{if(r=s.next(),r.done)break;n=r.value}var a=n;this.registerBinding(t.node.kind,a)}else if(t.isClassDeclaration())this.registerBinding("let",t);else if(t.isImportDeclaration())for(var o=t.get("specifiers"),p=o,c=Array.isArray(p),l=0,p=c?p:u(p);;){var h;if(c){if(l>=p.length)break;h=p[l++]}else{if(l=p.next(),l.done)break;h=l.value}var f=h;this.registerBinding("module",f)}else if(t.isExportDeclaration()){var a=t.get("declaration");(a.isClassDeclaration()||a.isFunctionDeclaration()||a.isVariableDeclaration())&&this.registerDeclaration(a)}else this.registerBinding("unknown",t)},t.prototype.buildUndefinedNode=function(){return this.hasBinding("undefined")?T.unaryExpression("void",T.numericLiteral(0),!0):T.identifier("undefined")},t.prototype.registerConstantViolation=function(t){var e=t.getBindingIdentifiers();for(var s in e){var i=this.getBinding(s);i&&i.reassign(t)}},t.prototype.registerBinding=function(t,e){var s=arguments.length<=2||void 0===arguments[2]?e:arguments[2];return function(){if(!t)throw new ReferenceError("no `kind`");if(e.isVariableDeclaration())for(var i=e.get("declarations"),r=i,n=Array.isArray(r),a=0,r=n?r:u(r);;){var o;if(n){if(a>=r.length)break;o=r[a++]}else{if(a=r.next(),a.done)break;o=a.value}var p=o;this.registerBinding(t,p)}else{var c=this.getProgramParent(),l=e.getBindingIdentifiers(!0);for(var h in l)for(var f=l[h],d=Array.isArray(f),y=0,f=d?f:u(f);;){var m;if(d){if(y>=f.length)break;m=f[y++]}else{if(y=f.next(),y.done)break;m=y.value}var v=m,g=this.getOwnBinding(h);if(g){if(g.identifier===v)continue;this.checkBlockScopedCollisions(g,t,h,v)}c.references[h]=!0,this.bindings[h]=new S["default"]({identifier:v,existing:g,scope:this,path:s,kind:t})}}}.apply(this,arguments)},t.prototype.addGlobal=function(t){this.globals[t.name]=t},t.prototype.hasUid=function(t){var e=this;do if(e.uids[t])return!0;while(e=e.parent);return!1},t.prototype.hasGlobal=function(t){var e=this;do if(e.globals[t])return!0;while(e=e.parent);return!1},t.prototype.hasReference=function(t){var e=this;do if(e.references[t])return!0;while(e=e.parent);return!1},t.prototype.isPure=function(t,e){if(T.isIdentifier(t)){var s=this.getBinding(t.name);return s?e?s.constant:!0:!1}if(T.isClass(t))return t.superClass&&!this.isPure(t.superClass,e)?!1:this.isPure(t.body,e);if(T.isClassBody(t)){for(var i=t.body,r=Array.isArray(i),n=0,i=r?i:u(i);;){ var a;if(r){if(n>=i.length)break;a=i[n++]}else{if(n=i.next(),n.done)break;a=n.value}var o=a;if(!this.isPure(o,e))return!1}return!0}if(T.isBinary(t))return this.isPure(t.left,e)&&this.isPure(t.right,e);if(T.isArrayExpression(t)){for(var p=t.elements,c=Array.isArray(p),l=0,p=c?p:u(p);;){var h;if(c){if(l>=p.length)break;h=p[l++]}else{if(l=p.next(),l.done)break;h=l.value}var f=h;if(!this.isPure(f,e))return!1}return!0}if(T.isObjectExpression(t)){for(var d=t.properties,y=Array.isArray(d),m=0,d=y?d:u(d);;){var v;if(y){if(m>=d.length)break;v=d[m++]}else{if(m=d.next(),m.done)break;v=m.value}var g=v;if(!this.isPure(g,e))return!1}return!0}return T.isClassMethod(t)?t.computed&&!this.isPure(t.key,e)?!1:"get"===t.kind||"set"===t.kind?!1:!0:T.isClassProperty(t)||T.isObjectProperty(t)?t.computed&&!this.isPure(t.key,e)?!1:this.isPure(t.value,e):T.isUnaryExpression(t)?this.isPure(t.argument,e):T.isPureish(t)},t.prototype.setData=function(t,e){return this.data[t]=e},t.prototype.getData=function(t){var e=this;do{var s=e.data[t];if(null!=s)return s}while(e=e.parent)},t.prototype.removeData=function(t){var e=this;do{var s=e.data[t];null!=s&&(e.data[t]=null)}while(e=e.parent)},t.prototype.init=function(){this.references||this.crawl()},t.prototype.crawl=function(){var t=this.path;if(this.references=p(null),this.bindings=p(null),this.globals=p(null),this.uids=p(null),this.data=p(null),t.isLoop())for(var e=T.FOR_INIT_KEYS,s=Array.isArray(e),i=0,e=s?e:u(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var n=r,a=t.get(n);a.isBlockScoped()&&this.registerBinding(a.node.kind,a)}if(t.isFunctionExpression()&&t.has("id")&&(t.get("id").node[T.NOT_LOCAL_BINDING]||this.registerBinding("local",t.get("id"),t)),t.isClassExpression()&&t.has("id")&&(t.get("id").node[T.NOT_LOCAL_BINDING]||this.registerBinding("local",t)),t.isFunction())for(var o=t.get("params"),c=o,l=Array.isArray(c),h=0,c=l?c:u(c);;){var f;if(l){if(h>=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}var d=f;this.registerBinding("param",d)}t.isCatchClause()&&this.registerBinding("let",t);var y=this.getProgramParent();if(!y.crawling){var m={references:[],constantViolations:[],assignments:[]};this.crawling=!0,t.traverse(_,m),this.crawling=!1;for(var v=m.assignments,g=Array.isArray(v),x=0,v=g?v:u(v);;){var A;if(g){if(x>=v.length)break;A=v[x++]}else{if(x=v.next(),x.done)break;A=x.value}var b=A,E=b.getBindingIdentifiers(),C=void 0;for(var D in E)b.scope.getBinding(D)||(C=C||b.scope.getProgramParent(),C.addGlobal(E[D]));b.scope.registerConstantViolation(b)}for(var S=m.references,F=Array.isArray(S),w=0,S=F?S:u(S);;){var k;if(F){if(w>=S.length)break;k=S[w++]}else{if(w=S.next(),w.done)break;k=w.value}var P=k,B=P.scope.getBinding(P.node.name);B?B.reference(P):P.scope.getProgramParent().addGlobal(P.node)}for(var N=m.constantViolations,L=Array.isArray(N),I=0,N=L?N:u(N);;){var O;if(L){if(I>=N.length)break;O=N[I++]}else{if(I=N.next(),I.done)break;O=I.value}var M=O;M.scope.registerConstantViolation(M)}}},t.prototype.push=function(t){var e=this.path;e.isBlockStatement()||e.isProgram()||(e=this.getBlockParent().path),e.isSwitchStatement()&&(e=this.getFunctionParent().path),(e.isLoop()||e.isCatchClause()||e.isFunction())&&(T.ensureBlock(e.node),e=e.get("body"));var s=t.unique,i=t.kind||"var",r=null==t._blockHoist?2:t._blockHoist,n="declaration:"+i+":"+r,a=!s&&e.getData(n);if(!a){var o=T.variableDeclaration(i,[]);o._generated=!0,o._blockHoist=r;var u=e.unshiftContainer("body",[o]);a=u[0],s||e.setData(n,a)}var p=T.variableDeclarator(t.id,t.init);a.node.declarations.push(p),this.registerBinding(i,a.get("declarations").pop())},t.prototype.getProgramParent=function(){var t=this;do if(t.path.isProgram())return t;while(t=t.parent);throw new Error("We couldn't find a Function or Program...")},t.prototype.getFunctionParent=function(){var t=this;do if(t.path.isFunctionParent())return t;while(t=t.parent);throw new Error("We couldn't find a Function or Program...")},t.prototype.getBlockParent=function(){var t=this;do if(t.path.isBlockParent())return t;while(t=t.parent);throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...")},t.prototype.getAllBindings=function(){var t=p(null),e=this;do b["default"](t,e.bindings),e=e.parent;while(e);return t},t.prototype.getAllBindingsOfKind=function(){for(var t=p(null),e=arguments,s=Array.isArray(e),i=0,e=s?e:u(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var n=r,a=this;do{for(var o in a.bindings){var c=a.bindings[o];c.kind===n&&(t[o]=c)}a=a.parent}while(a)}return t},t.prototype.bindingIdentifierEquals=function(t,e){return this.getBindingIdentifier(t)===e},t.prototype.getBinding=function(t){var e=this;do{var s=e.getOwnBinding(t);if(s)return s}while(e=e.parent)},t.prototype.getOwnBinding=function(t){return this.bindings[t]},t.prototype.getBindingIdentifier=function(t){var e=this.getBinding(t);return e&&e.identifier},t.prototype.getOwnBindingIdentifier=function(t){var e=this.bindings[t];return e&&e.identifier},t.prototype.hasOwnBinding=function(t){return!!this.getOwnBinding(t)},t.prototype.hasBinding=function(e,s){return e?this.hasOwnBinding(e)?!0:this.parentHasBinding(e,s)?!0:this.hasUid(e)?!0:!s&&f["default"](t.globals,e)?!0:!s&&f["default"](t.contextVariables,e)?!0:!1:!1},t.prototype.parentHasBinding=function(t,e){return this.parent&&this.parent.hasBinding(t,e)},t.prototype.moveBindingTo=function(t,e){var s=this.getBinding(t);s&&(s.scope.removeOwnBinding(t),s.scope=e,e.bindings[t]=s)},t.prototype.removeOwnBinding=function(t){delete this.bindings[t]},t.prototype.removeBinding=function(t){var e=this.getBinding(t);e&&e.scope.removeOwnBinding(t);var s=this;do s.uids[t]&&(s.uids[t]=!1);while(s=s.parent)},t}();e["default"]=N,t.exports=e["default"]},function(t,e,s){t.exports={"default":s(221),__esModule:!0}},function(t,e,s){s(174),s(222),t.exports=s(50).Symbol},function(t,e){},function(t,e,s){function i(t,e,s,i){var h=t?n(t):0;return u(h)||(t=c(t),h=t.length),s="number"!=typeof s||i&&o(e,s,i)?0:0>s?l(h+s,0):s||0,"string"==typeof t||!a(t)&&p(t)?h>=s&&t.indexOf(e,s)>-1:!!h&&r(t,e,s)>-1}var r=s(161),n=s(113),a=s(118),o=s(131),u=s(115),p=s(200),c=s(224),l=Math.max;t.exports=i},function(t,e,s){function i(t){return r(t,n(t))}var r=s(225),n=s(106);t.exports=i},function(t,e){function s(t,e){for(var s=-1,i=e.length,r=Array(i);++s<i;)r[s]=t[e[s]];return r}t.exports=s},function(t,e,s){"use strict";var i=s(227);t.exports=function(t,e){if("string"!=typeof t)throw new TypeError("Expected a string as the first argument");if(0>e||!i(e))throw new TypeError("Expected a finite positive number");var s="";do 1&e&&(s+=t),t+=t;while(e>>=1);return s}},function(t,e,s){"use strict";var i=s(228);t.exports=Number.isFinite||function(t){return!("number"!=typeof t||i(t)||t===1/0||t===-(1/0))}},function(t,e){"use strict";t.exports=Number.isNaN||function(t){return t!==t}},function(t,e,s){"use strict";var i=s(207)["default"],r=s(85)["default"],n=s(86)["default"];e.__esModule=!0;var a=s(230),o=(r(a),s(41)),u=n(o),p={ReferencedIdentifier:function(t,e){var s=t.node;s.name===e.oldName&&(s.name=e.newName)},Scope:function(t,e){t.scope.bindingIdentifierEquals(e.oldName,e.binding.identifier)||t.skip()},"AssignmentExpression|Declaration":function(t,e){var s=t.getOuterBindingIdentifiers();for(var i in s)i===e.oldName&&(s[i].name=e.newName)}},c=function(){function t(e,s,r){i(this,t),this.newName=r,this.oldName=s,this.binding=e}return t.prototype.maybeConvertFromExportDeclaration=function(t){var e=t.parentPath.isExportDeclaration()&&t.parentPath;if(e){var s=e.isExportDefaultDeclaration();s&&(t.isFunctionDeclaration()||t.isClassDeclaration())&&!t.node.id&&(t.node.id=t.scope.generateUidIdentifier("default"));var i=t.getOuterBindingIdentifiers(),r=[];for(var n in i){var a=n===this.oldName?this.newName:n,o=s?"default":n;r.push(u.exportSpecifier(u.identifier(a),u.identifier(o)))}var p=u.exportNamedDeclaration(null,r);t.isFunctionDeclaration()&&(p._blockHoist=3),e.insertAfter(p),e.replaceWith(t.node)}},t.prototype.maybeConvertFromClassFunctionDeclaration=function(t){},t.prototype.maybeConvertFromClassFunctionExpression=function(t){},t.prototype.rename=function(t){var e=this.binding,s=this.oldName,i=this.newName,r=e.scope,n=e.path,a=n.find(function(t){return t.isDeclaration()||t.isFunctionExpression()});a&&this.maybeConvertFromExportDeclaration(a),r.traverse(t||r.block,p,this),t||(r.removeOwnBinding(s),r.bindings[i]=e,this.binding.identifier.name=i),"hoisted"===e.type,a&&(this.maybeConvertFromClassFunctionDeclaration(a),this.maybeConvertFromClassFunctionExpression(a))},t}();e["default"]=c,t.exports=e["default"]},function(t,e,s){"use strict";var i=s(207)["default"];e.__esModule=!0;var r=function(){function t(e){var s=e.existing,r=e.identifier,n=e.scope,a=e.path,o=e.kind;i(this,t),this.identifier=r,this.scope=n,this.path=a,this.kind=o,this.constantViolations=[],this.constant=!0,this.referencePaths=[],this.referenced=!1,this.references=0,this.clearValue(),s&&(this.constantViolations=[].concat(s.path,s.constantViolations,this.constantViolations))}return t.prototype.deoptValue=function(){this.clearValue(),this.hasDeoptedValue=!0},t.prototype.setValue=function(t){this.hasDeoptedValue||(this.hasValue=!0,this.value=t)},t.prototype.clearValue=function(){this.hasDeoptedValue=!1,this.hasValue=!1,this.value=null},t.prototype.reassign=function(t){this.constant=!1,this.constantViolations.push(t)},t.prototype.reference=function(t){this.referenced=!0,this.references++,this.referencePaths.push(t)},t.prototype.dereference=function(){this.references--,this.referenced=!!this.references},t}();e["default"]=r,t.exports=e["default"]},function(t,e,s){var i=s(215),r=s(232),n=s(233),a=n(i,r);t.exports=a},function(t,e){function s(t,e){return void 0===t?e:t}t.exports=s},function(t,e,s){function i(t,e){return r(function(s){var i=s[0];return null==i?i:(s.push(e),t.apply(void 0,s))})}var r=s(218);t.exports=i},function(t,e,s){"use strict";function i(t){for(var e=arguments.length,s=Array(e>1?e-1:0),i=1;e>i;i++)s[i-1]=arguments[i];var n=u[t];if(!n)throw new ReferenceError("Unknown message "+JSON.stringify(t));return s=r(s),n.replace(/\$(\d+)/g,function(t,e){return s[e-1]})}function r(t){return t.map(function(t){if(null!=t&&t.inspect)return t.inspect();try{return JSON.stringify(t)||t+""}catch(e){return o.inspect(t)}})}var n=s(86)["default"];e.__esModule=!0,e.get=i,e.parseArgs=r;var a=s(235),o=n(a),u={tailCallReassignmentDeopt:"Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence",classesIllegalBareSuper:"Illegal use of bare super",classesIllegalSuperCall:"Direct super call is illegal in non-constructor, use super.$1() instead",scopeDuplicateDeclaration:"Duplicate declaration $1",settersNoRest:"Setters aren't allowed to have a rest",noAssignmentsInForHead:"No assignments allowed in for-in/of head",expectedMemberExpressionOrIdentifier:"Expected type MemberExpression or Identifier",invalidParentForThisNode:"We don't know how to handle this node within the current parent - please open an issue",readOnly:"$1 is read-only",unknownForHead:"Unknown node type $1 in ForStatement",didYouMean:"Did you mean $1?",codeGeneratorDeopt:"Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",missingTemplatesDirectory:"no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",unsupportedOutputType:"Unsupported output type $1",illegalMethodName:"Illegal method name $1",lostTrackNodePath:"We lost track of this node's position, likely because the AST was directly manipulated",modulesIllegalExportName:"Illegal export $1",modulesDuplicateDeclarations:"Duplicate module declarations with the same source but in different scopes",undeclaredVariable:"Reference to undeclared variable $1",undeclaredVariableType:"Referencing a type alias outside of a type annotation",undeclaredVariableSuggestion:"Reference to undeclared variable $1 - did you mean $2?",traverseNeedsParent:"You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.",traverseVerifyRootFunction:"You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?",traverseVerifyVisitorProperty:"You passed `traverse()` a visitor object with the property $1 that has the invalid property $2",traverseVerifyNodeType:"You gave us a visitor for the node type $1 but it's not a valid type",pluginNotObject:"Plugin $2 specified in $1 was expected to return an object when invoked but returned $3",pluginNotFunction:"Plugin $2 specified in $1 was expected to return a function but returned $3",pluginUnknown:"Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4",pluginInvalidProperty:"Plugin $2 specified in $1 provided an invalid property of $3"};e.MESSAGES=u},function(t,e,s){(function(t,i){function r(t,s){var i={seen:[],stylize:a};return arguments.length>=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),y(s)?i.showHidden=s:s&&e._extend(i,s),b(i.showHidden)&&(i.showHidden=!1),b(i.depth)&&(i.depth=2),b(i.colors)&&(i.colors=!1),b(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=n),u(i,t,i.depth)}function n(t,e){var s=r.styles[e];return s?"["+r.colors[s][0]+"m"+t+"["+r.colors[s][1]+"m":t}function a(t,e){return t}function o(t){var e={};return t.forEach(function(t,s){e[t]=!0}),e}function u(t,s,i){if(t.customInspect&&s&&F(s.inspect)&&s.inspect!==e.inspect&&(!s.constructor||s.constructor.prototype!==s)){var r=s.inspect(i,t);return x(r)||(r=u(t,r,i)),r}var n=p(t,s);if(n)return n;var a=Object.keys(s),y=o(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(s)),S(s)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(s);if(0===a.length){if(F(s)){var m=s.name?": "+s.name:"";return t.stylize("[Function"+m+"]","special")}if(E(s))return t.stylize(RegExp.prototype.toString.call(s),"regexp");if(D(s))return t.stylize(Date.prototype.toString.call(s),"date");if(S(s))return c(s)}var v="",g=!1,A=["{","}"];if(d(s)&&(g=!0,A=["[","]"]),F(s)){var b=s.name?": "+s.name:"";v=" [Function"+b+"]"}if(E(s)&&(v=" "+RegExp.prototype.toString.call(s)),D(s)&&(v=" "+Date.prototype.toUTCString.call(s)),S(s)&&(v=" "+c(s)),0===a.length&&(!g||0==s.length))return A[0]+v+A[1];if(0>i)return E(s)?t.stylize(RegExp.prototype.toString.call(s),"regexp"):t.stylize("[Object]","special");t.seen.push(s);var C;return C=g?l(t,s,i,y,a):a.map(function(e){return h(t,s,i,y,e,g)}),t.seen.pop(),f(C,v,A)}function p(t,e){if(b(e))return t.stylize("undefined","undefined");if(x(e)){var s="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(s,"string")}return g(e)?t.stylize(""+e,"number"):y(e)?t.stylize(""+e,"boolean"):m(e)?t.stylize("null","null"):void 0}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function l(t,e,s,i,r){for(var n=[],a=0,o=e.length;o>a;++a)_(e,String(a))?n.push(h(t,e,s,i,String(a),!0)):n.push("");return r.forEach(function(r){r.match(/^\d+$/)||n.push(h(t,e,s,i,r,!0))}),n}function h(t,e,s,i,r,n){var a,o,p;if(p=Object.getOwnPropertyDescriptor(e,r)||{value:e[r]},p.get?o=p.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):p.set&&(o=t.stylize("[Setter]","special")),_(i,r)||(a="["+r+"]"),o||(t.seen.indexOf(p.value)<0?(o=m(s)?u(t,p.value,null):u(t,p.value,s-1),o.indexOf("\n")>-1&&(o=n?o.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+o.split("\n").map(function(t){return" "+t}).join("\n"))):o=t.stylize("[Circular]","special")),b(a)){if(n&&r.match(/^\d+$/))return o;a=JSON.stringify(""+r),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+o}function f(t,e,s){var i=0,r=t.reduce(function(t,e){return i++,e.indexOf("\n")>=0&&i++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);return r>60?s[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+s[1]:s[0]+e+" "+t.join(", ")+" "+s[1]}function d(t){return Array.isArray(t)}function y(t){return"boolean"==typeof t}function m(t){return null===t}function v(t){return null==t}function g(t){return"number"==typeof t}function x(t){return"string"==typeof t}function A(t){return"symbol"==typeof t}function b(t){return void 0===t}function E(t){return C(t)&&"[object RegExp]"===T(t)}function C(t){return"object"==typeof t&&null!==t}function D(t){return C(t)&&"[object Date]"===T(t)}function S(t){return C(t)&&("[object Error]"===T(t)||t instanceof Error)}function F(t){return"function"==typeof t}function w(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t}function T(t){return Object.prototype.toString.call(t)}function k(t){return 10>t?"0"+t.toString(10):t.toString(10)}function P(){var t=new Date,e=[k(t.getHours()),k(t.getMinutes()),k(t.getSeconds())].join(":");return[t.getDate(),I[t.getMonth()],e].join(" ")}function _(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var B=/%[sdj%]/g;e.format=function(t){if(!x(t)){for(var e=[],s=0;s<arguments.length;s++)e.push(r(arguments[s]));return e.join(" ")}for(var s=1,i=arguments,n=i.length,a=String(t).replace(B,function(t){if("%%"===t)return"%";if(s>=n)return t;switch(t){case"%s":return String(i[s++]);case"%d":return Number(i[s++]);case"%j":try{return JSON.stringify(i[s++])}catch(e){return"[Circular]"}default:return t}}),o=i[s];n>s;o=i[++s])a+=m(o)||!C(o)?" "+o:" "+r(o);return a},e.deprecate=function(s,r){function n(){if(!a){if(i.throwDeprecation)throw new Error(r);i.traceDeprecation?console.trace(r):console.error(r),a=!0}return s.apply(this,arguments)}if(b(t.process))return function(){return e.deprecate(s,r).apply(this,arguments)};if(i.noDeprecation===!0)return s;var a=!1;return n};var N,L={};e.debuglog=function(t){if(b(N)&&(N=i.env.NODE_DEBUG||""),t=t.toUpperCase(),!L[t])if(new RegExp("\\b"+t+"\\b","i").test(N)){var s=i.pid;L[t]=function(){var i=e.format.apply(e,arguments);console.error("%s %d: %s",t,s,i)}}else L[t]=function(){};return L[t]},e.inspect=r,r.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},r.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=d,e.isBoolean=y,e.isNull=m,e.isNullOrUndefined=v,e.isNumber=g,e.isString=x,e.isSymbol=A,e.isUndefined=b,e.isRegExp=E,e.isObject=C,e.isDate=D,e.isError=S,e.isFunction=F,e.isPrimitive=w,e.isBuffer=s(236);var I=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];e.log=function(){console.log("%s - %s",P(),e.format.apply(e,arguments))},e.inherits=s(237),e._extend=function(t,e){if(!e||!C(e))return t;for(var s=Object.keys(e),i=s.length;i--;)t[s[i]]=e[s[i]];return t}}).call(e,function(){return this}(),s(206))},function(t,e){t.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},function(t,e){"function"==typeof Object.create?t.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(t,e){t.super_=e;var s=function(){};s.prototype=e.prototype,t.prototype=new s,t.prototype.constructor=t}},function(t,e,s){t.exports=s(239)},function(t,e){t.exports={builtin:{Array:!1,ArrayBuffer:!1,Boolean:!1,constructor:!1,DataView:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,escape:!1,eval:!1,EvalError:!1,Float32Array:!1,Float64Array:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Map:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,Promise:!1,propertyIsEnumerable:!1,Proxy:!1,RangeError:!1,ReferenceError:!1,Reflect:!1,RegExp:!1,Set:!1,String:!1,Symbol:!1,SyntaxError:!1,System:!1,toLocaleString:!1,toString:!1,TypeError:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1,undefined:!1,unescape:!1,URIError:!1,valueOf:!1,WeakMap:!1,WeakSet:!1},es5:{Array:!1,Boolean:!1,constructor:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,escape:!1,eval:!1,EvalError:!1,Float32Array:!1,Float64Array:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,propertyIsEnumerable:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,toLocaleString:!1,toString:!1,TypeError:!1,undefined:!1,unescape:!1,URIError:!1,valueOf:!1},es6:{Array:!1,ArrayBuffer:!1,Boolean:!1,constructor:!1,DataView:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,escape:!1,eval:!1,EvalError:!1,Float32Array:!1,Float64Array:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Map:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,Promise:!1,propertyIsEnumerable:!1,Proxy:!1,RangeError:!1,ReferenceError:!1,Reflect:!1,RegExp:!1,Set:!1,String:!1,Symbol:!1,SyntaxError:!1,System:!1,toLocaleString:!1,toString:!1,TypeError:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1,undefined:!1,unescape:!1,URIError:!1,valueOf:!1,WeakMap:!1,WeakSet:!1},browser:{addEventListener:!1,alert:!1,AnalyserNode:!1,AnimationEvent:!1,applicationCache:!1,ApplicationCache:!1,ApplicationCacheErrorEvent:!1,atob:!1,Attr:!1,Audio:!1,AudioBuffer:!1,AudioBufferSourceNode:!1,AudioContext:!1,AudioDestinationNode:!1,AudioListener:!1,AudioNode:!1,AudioParam:!1,AudioProcessingEvent:!1,AutocompleteErrorEvent:!1,BarProp:!1,BatteryManager:!1,BeforeUnloadEvent:!1,BiquadFilterNode:!1,Blob:!1,blur:!1,btoa:!1,Cache:!1,caches:!1,CacheStorage:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CDATASection:!1,ChannelMergerNode:!1,ChannelSplitterNode:!1,CharacterData:!1,clearInterval:!1,clearTimeout:!1,clientInformation:!1,ClientRect:!1,ClientRectList:!1,ClipboardEvent:!1,close:!1,closed:!1,CloseEvent:!1,Comment:!1,CompositionEvent:!1,confirm:!1,console:!1,ConvolverNode:!1,crypto:!1,Crypto:!1,CryptoKey:!1,CSS:!1,CSSFontFaceRule:!1,CSSImportRule:!1,CSSKeyframeRule:!1,CSSKeyframesRule:!1,CSSMediaRule:!1,CSSPageRule:!1,CSSRule:!1,CSSRuleList:!1,CSSStyleDeclaration:!1,CSSStyleRule:!1,CSSStyleSheet:!1,CSSSupportsRule:!1,CSSUnknownRule:!1,CSSViewportRule:!1,CustomEvent:!1,DataTransfer:!1,DataTransferItem:!1,DataTransferItemList:!1,Debug:!1,defaultStatus:!1,defaultstatus:!1,DelayNode:!1,DeviceMotionEvent:!1,DeviceOrientationEvent:!1,devicePixelRatio:!1,dispatchEvent:!1,document:!1,Document:!1,DocumentFragment:!1,DocumentType:!1,DOMError:!1,DOMException:!1,DOMImplementation:!1,DOMParser:!1,DOMSettableTokenList:!1,DOMStringList:!1,DOMStringMap:!1,DOMTokenList:!1,DragEvent:!1,DynamicsCompressorNode:!1,Element:!1,ElementTimeControl:!1,ErrorEvent:!1,event:!1,Event:!1,EventSource:!1,EventTarget:!1,external:!1,fetch:!1,File:!1,FileError:!1,FileList:!1,FileReader:!1,find:!1,focus:!1,FocusEvent:!1,FontFace:!1,FormData:!1,frameElement:!1,frames:!1,GainNode:!1,Gamepad:!1,GamepadButton:!1,GamepadEvent:!1,getComputedStyle:!1,getSelection:!1,HashChangeEvent:!1,Headers:!1,history:!1,History:!1,HTMLAllCollection:!1,HTMLAnchorElement:!1,HTMLAppletElement:!1,HTMLAreaElement:!1,HTMLAudioElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLContentElement:!1,HTMLDataListElement:!1,HTMLDetailsElement:!1,HTMLDialogElement:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLDocument:!1,HTMLElement:!1,HTMLEmbedElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormControlsCollection:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLKeygenElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMarqueeElement:!1,HTMLMediaElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLMeterElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLOptionsCollection:!1,HTMLOutputElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPictureElement:!1,HTMLPreElement:!1,HTMLProgressElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLShadowElement:!1,HTMLSourceElement:!1,HTMLSpanElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLTrackElement:!1,HTMLUListElement:!1,HTMLUnknownElement:!1,HTMLVideoElement:!1,IDBCursor:!1,IDBCursorWithValue:!1,IDBDatabase:!1,IDBEnvironment:!1,IDBFactory:!1,IDBIndex:!1,IDBKeyRange:!1,IDBObjectStore:!1,IDBOpenDBRequest:!1,IDBRequest:!1,IDBTransaction:!1,IDBVersionChangeEvent:!1,Image:!1,ImageBitmap:!1,ImageData:!1,indexedDB:!1,innerHeight:!1,innerWidth:!1,InputEvent:!1,InputMethodContext:!1,Intl:!1,KeyboardEvent:!1,length:!1,localStorage:!1,location:!1,Location:!1,locationbar:!1,matchMedia:!1,MediaElementAudioSourceNode:!1,MediaEncryptedEvent:!1,MediaError:!1,MediaKeyError:!1,MediaKeyEvent:!1,MediaKeyMessageEvent:!1,MediaKeys:!1,MediaKeySession:!1,MediaKeyStatusMap:!1,MediaKeySystemAccess:!1,MediaList:!1,MediaQueryList:!1,MediaQueryListEvent:!1,MediaSource:!1,MediaStreamAudioDestinationNode:!1,MediaStreamAudioSourceNode:!1,MediaStreamEvent:!1,MediaStreamTrack:!1,menubar:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MIDIAccess:!1,MIDIConnectionEvent:!1,MIDIInput:!1,MIDIInputMap:!1,MIDIMessageEvent:!1,MIDIOutput:!1,MIDIOutputMap:!1,MIDIPort:!1,MimeType:!1,MimeTypeArray:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationEvent:!1,MutationObserver:!1,MutationRecord:!1,name:!1,NamedNodeMap:!1,navigator:!1,Navigator:!1,Node:!1,NodeFilter:!1,NodeIterator:!1,NodeList:!1,Notification:!1,OfflineAudioCompletionEvent:!1,OfflineAudioContext:!1,offscreenBuffering:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,opera:!1,Option:!1,OscillatorNode:!1,outerHeight:!1,outerWidth:!1,PageTransitionEvent:!1,pageXOffset:!1,pageYOffset:!1,parent:!1,Path2D:!1,performance:!1,Performance:!1,PerformanceEntry:!1,PerformanceMark:!1,PerformanceMeasure:!1,PerformanceNavigation:!1,PerformanceResourceTiming:!1,PerformanceTiming:!1,PeriodicWave:!1,Permissions:!1,PermissionStatus:!1,personalbar:!1,Plugin:!1,PluginArray:!1,PopStateEvent:!1,postMessage:!1,print:!1,ProcessingInstruction:!1,ProgressEvent:!1,prompt:!1,PushManager:!1,PushSubscription:!1,RadioNodeList:!1,Range:!1,ReadableByteStream:!1,ReadableStream:!1,removeEventListener:!1,Request:!1,requestAnimationFrame:!1,resizeBy:!1,resizeTo:!1,Response:!1,RTCIceCandidate:!1,RTCSessionDescription:!1,screen:!1,Screen:!1,screenLeft:!1,ScreenOrientation:!1,screenTop:!1,screenX:!1,screenY:!1,ScriptProcessorNode:!1,scroll:!1,scrollbars:!1,scrollBy:!1,scrollTo:!1,scrollX:!1,scrollY:!1,SecurityPolicyViolationEvent:!1,Selection:!1,self:!1,ServiceWorker:!1,ServiceWorkerContainer:!1,ServiceWorkerRegistration:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,ShadowRoot:!1,SharedWorker:!1,showModalDialog:!1,speechSynthesis:!1,SpeechSynthesisEvent:!1,SpeechSynthesisUtterance:!1,status:!1,statusbar:!1,stop:!1,Storage:!1,StorageEvent:!1,styleMedia:!1,StyleSheet:!1,StyleSheetList:!1,SubtleCrypto:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimationElement:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCSSRule:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDiscardElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGEvent:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEDropShadowElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGeometryElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGGraphicsElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLinearGradientElement:!1,SVGLineElement:!1,SVGLocatable:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGMPathElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSVGElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformable:!1,SVGTransformList:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGUnitTypes:!1,SVGURIReference:!1,SVGUseElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGVKernElement:!1,SVGZoomAndPan:!1,SVGZoomEvent:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TextEvent:!1,TextMetrics:!1,TextTrack:!1,TextTrackCue:!1,TextTrackCueList:!1,TextTrackList:!1,TimeEvent:!1,TimeRanges:!1,toolbar:!1,top:!1,Touch:!1,TouchEvent:!1,TouchList:!1,TrackEvent:!1,TransitionEvent:!1,TreeWalker:!1,UIEvent:!1,URL:!1,ValidityState:!1,VTTCue:!1,WaveShaperNode:!1,WebGLActiveInfo:!1, WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,WheelEvent:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLDocument:!1,XMLHttpRequest:!1,XMLHttpRequestEventTarget:!1,XMLHttpRequestProgressEvent:!1,XMLHttpRequestUpload:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1,XSLTProcessor:!1},worker:{applicationCache:!1,atob:!1,Blob:!1,BroadcastChannel:!1,btoa:!1,Cache:!1,caches:!1,clearInterval:!1,clearTimeout:!1,close:!0,console:!1,fetch:!1,FileReaderSync:!1,FormData:!1,Headers:!1,IDBCursor:!1,IDBCursorWithValue:!1,IDBDatabase:!1,IDBFactory:!1,IDBIndex:!1,IDBKeyRange:!1,IDBObjectStore:!1,IDBOpenDBRequest:!1,IDBRequest:!1,IDBTransaction:!1,IDBVersionChangeEvent:!1,ImageData:!1,importScripts:!0,indexedDB:!1,location:!1,MessageChannel:!1,MessagePort:!1,name:!1,navigator:!1,Notification:!1,onclose:!0,onconnect:!0,onerror:!0,onlanguagechange:!0,onmessage:!0,onoffline:!0,ononline:!0,onrejectionhandled:!0,onunhandledrejection:!0,performance:!1,Performance:!1,PerformanceEntry:!1,PerformanceMark:!1,PerformanceMeasure:!1,PerformanceNavigation:!1,PerformanceResourceTiming:!1,PerformanceTiming:!1,postMessage:!0,Promise:!1,Request:!1,Response:!1,self:!0,ServiceWorkerRegistration:!1,setInterval:!1,setTimeout:!1,TextDecoder:!1,TextEncoder:!1,URL:!1,WebSocket:!1,Worker:!1,XMLHttpRequest:!1},node:{__dirname:!1,__filename:!1,arguments:!1,Buffer:!1,clearImmediate:!1,clearInterval:!1,clearTimeout:!1,console:!1,exports:!0,GLOBAL:!1,global:!1,module:!1,process:!1,require:!1,root:!1,setImmediate:!1,setInterval:!1,setTimeout:!1},commonjs:{exports:!0,module:!1,require:!1,global:!1},amd:{define:!1,require:!1},mocha:{after:!1,afterEach:!1,before:!1,beforeEach:!1,context:!1,describe:!1,it:!1,mocha:!1,setup:!1,specify:!1,suite:!1,suiteSetup:!1,suiteTeardown:!1,teardown:!1,test:!1,xcontext:!1,xdescribe:!1,xit:!1,xspecify:!1},jasmine:{afterAll:!1,afterEach:!1,beforeAll:!1,beforeEach:!1,describe:!1,expect:!1,fail:!1,fdescribe:!1,fit:!1,it:!1,jasmine:!1,pending:!1,runs:!1,spyOn:!1,waits:!1,waitsFor:!1,xdescribe:!1,xit:!1},jest:{afterEach:!1,beforeEach:!1,describe:!1,expect:!1,it:!1,jest:!1,pit:!1,require:!1,xdescribe:!1,xit:!1},qunit:{asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notOk:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,"throws":!1},phantomjs:{console:!0,exports:!0,phantom:!0,require:!0,WebPage:!0},couch:{emit:!1,exports:!1,getRow:!1,log:!1,module:!1,provides:!1,require:!1,respond:!1,send:!1,start:!1,sum:!1},rhino:{defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},nashorn:{__DIR__:!1,__FILE__:!1,__LINE__:!1,com:!1,edu:!1,exit:!1,Java:!1,java:!1,javafx:!1,JavaImporter:!1,javax:!1,JSAdapter:!1,load:!1,loadWithNewGlobal:!1,org:!1,Packages:!1,print:!1,quit:!1},wsh:{ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WScript:!0,WSH:!0,XDomainRequest:!0},jquery:{$:!1,jQuery:!1},yui:{Y:!1,YUI:!1,YUI_config:!1},shelljs:{cat:!1,cd:!1,chmod:!1,config:!1,cp:!1,dirs:!1,echo:!1,env:!1,error:!1,exec:!1,exit:!1,find:!1,grep:!1,ls:!1,ln:!1,mkdir:!1,mv:!1,popd:!1,pushd:!1,pwd:!1,rm:!1,sed:!1,target:!1,tempdir:!1,test:!1,which:!1},prototypejs:{$:!1,$$:!1,$A:!1,$break:!1,$continue:!1,$F:!1,$H:!1,$R:!1,$w:!1,Abstract:!1,Ajax:!1,Autocompleter:!1,Builder:!1,Class:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Element:!1,Enumerable:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Scriptaculous:!1,Selector:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Template:!1,Toggle:!1,Try:!1},meteor:{$:!1,_:!1,Accounts:!1,App:!1,Assets:!1,Blaze:!1,check:!1,Cordova:!1,DDP:!1,DDPServer:!1,Deps:!1,EJSON:!1,Email:!1,HTTP:!1,Log:!1,Match:!1,Meteor:!1,Mongo:!1,MongoInternals:!1,Npm:!1,Package:!1,Plugin:!1,process:!1,Random:!1,ReactiveDict:!1,ReactiveVar:!1,Router:!1,Session:!1,share:!1,Spacebars:!1,Template:!1,Tinytest:!1,Tracker:!1,UI:!1,Utils:!1,WebApp:!1,WebAppInternals:!1},mongo:{_isWindows:!1,_rand:!1,BulkWriteResult:!1,cat:!1,cd:!1,connect:!1,db:!1,getHostName:!1,getMemInfo:!1,hostname:!1,listFiles:!1,load:!1,ls:!1,md5sumFile:!1,mkdir:!1,Mongo:!1,ObjectId:!1,PlanCache:!1,print:!1,printjson:!1,pwd:!1,quit:!1,removeFile:!1,rs:!1,sh:!1,UUID:!1,version:!1,WriteResult:!1},applescript:{$:!1,Application:!1,Automation:!1,console:!1,delay:!1,Library:!1,ObjC:!1,ObjectSpecifier:!1,Path:!1,Progress:!1,Ref:!1},serviceworker:{caches:!1,Cache:!1,CacheStorage:!1,Client:!1,clients:!1,Clients:!1,ExtendableEvent:!1,ExtendableMessageEvent:!1,FetchEvent:!1,importScripts:!1,registration:!1,self:!1,ServiceWorker:!1,ServiceWorkerContainer:!1,ServiceWorkerGlobalScope:!1,ServiceWorkerMessageEvent:!1,ServiceWorkerRegistration:!1,skipWaiting:!1,WindowClient:!1},atomtest:{advanceClock:!1,fakeClearInterval:!1,fakeClearTimeout:!1,fakeSetInterval:!1,fakeSetTimeout:!1,resetTimeouts:!1,waitsForPromise:!1},embertest:{andThen:!1,click:!1,currentPath:!1,currentRouteName:!1,currentURL:!1,fillIn:!1,find:!1,findWithAssert:!1,keyEvent:!1,pauseTest:!1,triggerEvent:!1,visit:!1},protractor:{$:!1,$$:!1,browser:!1,By:!1,by:!1,DartObject:!1,element:!1,protractor:!1},"shared-node-browser":{clearInterval:!1,clearTimeout:!1,console:!1,setInterval:!1,setTimeout:!1},webextensions:{browser:!1,chrome:!1,opr:!1},greasemonkey:{GM_addStyle:!1,GM_deleteValue:!1,GM_getResourceText:!1,GM_getResourceURL:!1,GM_getValue:!1,GM_info:!1,GM_listValues:!1,GM_log:!1,GM_openInTab:!1,GM_registerMenuCommand:!1,GM_setClipboard:!1,GM_setValue:!1,GM_xmlhttpRequest:!1,unsafeWindow:!1}}},function(t,e,s){"use strict";function i(t){for(var e=this;e=e.parentPath;)if(t(e))return e;return null}function r(t){var e=this;do if(t(e))return e;while(e=e.parentPath);return null}function n(){return this.findParent(function(t){return t.isFunction()||t.isProgram()})}function a(){var t=this;do if(Array.isArray(t.container))return t;while(t=t.parentPath)}function o(t){return this.getDeepestCommonAncestorFrom(t,function(t,e,s){for(var i=void 0,r=m.VISITOR_KEYS[t.type],n=s,a=Array.isArray(n),o=0,n=a?n:h(n);;){var u;if(a){if(o>=n.length)break;u=n[o++]}else{if(o=n.next(),o.done)break;u=o.value}var p=u,c=p[e+1];if(i)if(c.listKey&&i.listKey===c.listKey&&c.key<i.key)i=c;else{var l=r.indexOf(i.parentKey),f=r.indexOf(c.parentKey);l>f&&(i=c)}else i=c}return i})}function u(t,e){var s=this;if(!t.length)return this;if(1===t.length)return t[0];var i=1/0,r=void 0,n=void 0,a=t.map(function(t){var e=[];do e.unshift(t);while((t=t.parentPath)&&t!==s);return e.length<i&&(i=e.length),e}),o=a[0];t:for(var u=0;i>u;u++){for(var p=o[u],c=a,l=Array.isArray(c),f=0,c=l?c:h(c);;){var d;if(l){if(f>=c.length)break;d=c[f++]}else{if(f=c.next(),f.done)break;d=f.value}var y=d;if(y[u]!==p)break t}r=u,n=p}if(n)return e?e(n,r,a):n;throw new Error("Couldn't find intersection")}function p(){var t=this,e=[];do e.push(t);while(t=t.parentPath);return e}function c(){for(var t=this;t;){for(var e=arguments,s=Array.isArray(e),i=0,e=s?e:h(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var n=r;if(t.node.type===n)return!0}t=t.parentPath}return!1}function l(t){var e=this;do if(e.isFunction()){var s=e.node.shadow;if(s){if(!t||s[t]!==!1)return e}else if(e.isArrowFunctionExpression())return e;return null}while(e=e.parentPath);return null}var h=s(54)["default"],f=s(86)["default"],d=s(85)["default"];e.__esModule=!0,e.findParent=i,e.find=r,e.getFunctionParent=n,e.getStatementParent=a,e.getEarliestCommonAncestorFrom=o,e.getDeepestCommonAncestorFrom=u,e.getAncestry=p,e.inType=c,e.inShadow=l;var y=s(41),m=f(y),v=s(208);d(v)},function(t,e,s){"use strict";function i(){if(this.typeAnnotation)return this.typeAnnotation;var t=this._getTypeAnnotation()||y.anyTypeAnnotation();return y.isTypeAnnotation(t)&&(t=t.typeAnnotation),this.typeAnnotation=t}function r(){var t=this.node;{if(t){if(t.typeAnnotation)return t.typeAnnotation;var e=f[t.type];return e?e.call(this,t):(e=f[this.parentPath.type],e&&e.validParent?this.parentPath.getTypeAnnotation():void 0)}if("init"===this.key&&this.parentPath.isVariableDeclarator()){var s=this.parentPath.parentPath,i=s.parentPath;return"left"===s.key&&i.isForInStatement()?y.stringTypeAnnotation():"left"===s.key&&i.isForOfStatement()?y.anyTypeAnnotation():y.voidTypeAnnotation()}}}function n(t,e){return a(t,this.getTypeAnnotation(),e)}function a(t,e,s){if("string"===t)return y.isStringTypeAnnotation(e);if("number"===t)return y.isNumberTypeAnnotation(e);if("boolean"===t)return y.isBooleanTypeAnnotation(e);if("any"===t)return y.isAnyTypeAnnotation(e);if("mixed"===t)return y.isMixedTypeAnnotation(e);if("void"===t)return y.isVoidTypeAnnotation(e);if(s)return!1;throw new Error("Unknown base type "+t)}function o(t){var e=this.getTypeAnnotation();if(y.isAnyTypeAnnotation(e))return!0;if(y.isUnionTypeAnnotation(e)){for(var s=e.types,i=Array.isArray(s),r=0,s=i?s:c(s);;){var n;if(i){if(r>=s.length)break;n=s[r++]}else{if(r=s.next(),r.done)break;n=r.value}var o=n;if(y.isAnyTypeAnnotation(o)||a(t,o,!0))return!0}return!1}return a(t,e,!0)}function u(t){var e=this.getTypeAnnotation();return t=t.getTypeAnnotation(),!y.isAnyTypeAnnotation(e)&&y.isFlowBaseAnnotation(e)?t.type===e.type:void 0}function p(t){var e=this.getTypeAnnotation();return y.isGenericTypeAnnotation(e)&&y.isIdentifier(e.id,{name:t})}var c=s(54)["default"],l=s(86)["default"];e.__esModule=!0,e.getTypeAnnotation=i,e._getTypeAnnotation=r,e.isBaseType=n,e.couldBeBaseType=o,e.baseTypeStrictlyMatches=u,e.isGenericType=p;var h=s(242),f=l(h),d=s(41),y=l(d)},function(t,e,s){"use strict";function i(){var t=this.get("id");return t.isIdentifier()?this.get("init").getTypeAnnotation():void 0}function r(t){return t.typeAnnotation}function n(t){return this.get("callee").isIdentifier()?k.genericTypeAnnotation(t.callee):void 0}function a(){return k.stringTypeAnnotation()}function o(t){var e=t.operator;return"void"===e?k.voidTypeAnnotation():k.NUMBER_UNARY_OPERATORS.indexOf(e)>=0?k.numberTypeAnnotation():k.STRING_UNARY_OPERATORS.indexOf(e)>=0?k.stringTypeAnnotation():k.BOOLEAN_UNARY_OPERATORS.indexOf(e)>=0?k.booleanTypeAnnotation():void 0}function u(t){var e=t.operator;if(k.NUMBER_BINARY_OPERATORS.indexOf(e)>=0)return k.numberTypeAnnotation();if(k.BOOLEAN_BINARY_OPERATORS.indexOf(e)>=0)return k.booleanTypeAnnotation();if("+"===e){var s=this.get("right"),i=this.get("left");return i.isBaseType("number")&&s.isBaseType("number")?k.numberTypeAnnotation():i.isBaseType("string")||s.isBaseType("string")?k.stringTypeAnnotation():k.unionTypeAnnotation([k.stringTypeAnnotation(),k.numberTypeAnnotation()])}}function p(){return k.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(),this.get("right").getTypeAnnotation()])}function c(){return k.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(),this.get("alternate").getTypeAnnotation()])}function l(){return this.get("expressions").pop().getTypeAnnotation()}function h(){return this.get("right").getTypeAnnotation()}function f(t){var e=t.operator;return"++"===e||"--"===e?k.numberTypeAnnotation():void 0}function d(){return k.stringTypeAnnotation()}function y(){return k.numberTypeAnnotation()}function m(){return k.booleanTypeAnnotation()}function v(){return k.nullLiteralTypeAnnotation()}function g(){return k.genericTypeAnnotation(k.identifier("RegExp"))}function x(){return k.genericTypeAnnotation(k.identifier("Object"))}function A(){return k.genericTypeAnnotation(k.identifier("Array"))}function b(){return A()}function E(){return k.genericTypeAnnotation(k.identifier("Function"))}function C(){return S(this.get("callee"))}function D(){return S(this.get("tag"))}function S(t){if(t=t.resolve(),t.isFunction()){if(t.is("async"))return t.is("generator")?k.genericTypeAnnotation(k.identifier("AsyncIterator")):k.genericTypeAnnotation(k.identifier("Promise"));if(t.node.returnType)return t.node.returnType}}var F=s(86)["default"],w=s(204)["default"];e.__esModule=!0,e.VariableDeclarator=i,e.TypeCastExpression=r,e.NewExpression=n,e.TemplateLiteral=a,e.UnaryExpression=o,e.BinaryExpression=u,e.LogicalExpression=p,e.ConditionalExpression=c,e.SequenceExpression=l,e.AssignmentExpression=h,e.UpdateExpression=f,e.StringLiteral=d,e.NumericLiteral=y,e.BooleanLiteral=m,e.NullLiteral=v,e.RegExpLiteral=g,e.ObjectExpression=x,e.ArrayExpression=A,e.RestElement=b,e.CallExpression=C,e.TaggedTemplateExpression=D;var T=s(41),k=F(T),P=s(243);e.Identifier=w(P),r.validParent=!0,b.validParent=!0,e.Function=E,e.Class=E},function(t,e,s){"use strict";function i(t,e){var s=t.scope.getBinding(e),i=[];t.typeAnnotation=l.unionTypeAnnotation(i);var n=[],a=r(s,t,n),p=o(t,e);if(p&&!function(){var t=r(s,p.ifStatement);a=a.filter(function(e){return t.indexOf(e)<0}),i.push(p.typeAnnotation)}(),a.length){a=a.concat(n);for(var c=a,h=Array.isArray(c),f=0,c=h?c:u(c);;){var d;if(h){if(f>=c.length)break;d=c[f++]}else{if(f=c.next(),f.done)break;d=f.value}var y=d;i.push(y.getTypeAnnotation())}}return i.length?l.createUnionTypeAnnotation(i):void 0}function r(t,e,s){var i=t.constantViolations.slice();return i.unshift(t.path),i.filter(function(t){t=t.resolve();var i=t._guessExecutionStatusRelativeTo(e);return s&&"function"===i&&s.push(t),"before"===i})}function n(t,e){var s=e.node.operator,i=e.get("right").resolve(),r=e.get("left").resolve(),n=void 0;if(r.isIdentifier({name:t})?n=i:i.isIdentifier({name:t})&&(n=r),n)return"==="===s?n.getTypeAnnotation():l.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(s)>=0?l.numberTypeAnnotation():void 0;if("==="===s){var a=void 0,o=void 0;if(r.isUnaryExpression({operator:"typeof"})?(a=r,o=i):i.isUnaryExpression({operator:"typeof"})&&(a=i,o=r),(o||a)&&(o=o.resolve(),o.isLiteral())){var u=o.node.value;if("string"==typeof u&&a.get("argument").isIdentifier({name:t}))return l.createTypeAnnotationBasedOnTypeof(o.node.value)}}}function a(t){for(var e=void 0;e=t.parentPath;){if(e.isIfStatement()||e.isConditionalExpression())return"test"===t.key?void 0:e;t=e}}function o(t,e){var s=a(t);if(s){var i=s.get("test"),r=[i],u=[];do{var p=r.shift().resolve();if(p.isLogicalExpression()&&(r.push(p.get("left")),r.push(p.get("right"))),p.isBinaryExpression()){var c=n(e,p);c&&u.push(c)}}while(r.length);return u.length?{typeAnnotation:l.createUnionTypeAnnotation(u),ifStatement:s}:o(s,e)}}var u=s(54)["default"],p=s(86)["default"];e.__esModule=!0;var c=s(41),l=p(c);e["default"]=function(t){if(this.isReferenced()){var e=this.scope.getBinding(t.name);return e?e.identifier.typeAnnotation?e.identifier.typeAnnotation:i(this,t.name):"undefined"===t.name?l.voidTypeAnnotation():"NaN"===t.name||"Infinity"===t.name?l.numberTypeAnnotation():void("arguments"===t.name)}},t.exports=e["default"]},function(t,e,s){"use strict";function i(t){this.resync(),t=this._verifyNodeList(t),A.inheritLeadingComments(t[0],this.node),A.inheritTrailingComments(t[t.length-1],this.node),this.node=this.container[this.key]=null,this.insertAfter(t),this.node?this.requeue():this.remove()}function r(t){this.resync();try{t="("+t+")",t=g.parse(t)}catch(e){var s=e.loc;throw s&&(e.message+=" - make sure this is an expression.",e.message+="\n"+f["default"](t,s.line,s.column+1)),e}return t=t.program.body[0].expression,y["default"].removeProperties(t),this.replaceWith(t)}function n(t){if(this.resync(),this.removed)throw new Error("You can't replace this node, we've already removed it");if(t instanceof v["default"]&&(t=t.node),!t)throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");if(this.node!==t){if(this.isProgram()&&!A.isProgram(t))throw new Error("You can only replace a Program root node with another Program node");if(Array.isArray(t))throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");if("string"==typeof t)throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");if(this.isNodeType("Statement")&&A.isExpression(t)&&!this.canHaveVariableDeclarationOrExpression()&&(t=A.expressionStatement(t)),this.isNodeType("Expression")&&A.isStatement(t))return this.replaceExpressionWithStatements([t]);var e=this.node;e&&(A.inheritsComments(t,e),A.removeComments(e)),this._replaceWith(t),this.type=t.type,this.setScope(),this.requeue()}}function a(t){if(!this.container)throw new ReferenceError("Container is falsy");this.inList?A.validate(this.parent,this.key,[t]):A.validate(this.parent,this.key,t),this.debug(function(){return"Replace with "+(t&&t.type)}),this.node=this.container[this.key]=t}function o(t){this.resync();var e=A.toSequenceExpression(t,this.scope);if(A.isSequenceExpression(e)){var s=e.expressions;s.length>=2&&this.parentPath.isExpressionStatement()&&this._maybePopFromStatements(s),1===s.length?this.replaceWith(s[0]):this.replaceWith(e)}else{if(!e){var i=A.functionExpression(null,[],A.blockStatement(t));i.shadow=!0,this.replaceWith(A.callExpression(i,[])),this.traverse(b);for(var r=this.get("callee").getCompletionRecords(),n=r,a=Array.isArray(n),o=0,n=a?n:p(n);;){var u;if(a){if(o>=n.length)break;u=n[o++]}else{if(o=n.next(),o.done)break;u=o.value}var c=u;if(c.isExpressionStatement()){var l=c.findParent(function(t){return t.isLoop()});if(l){var h=this.get("callee"),f=h.scope.generateDeclaredUidIdentifier("ret");h.get("body").pushContainer("body",A.returnStatement(f)),c.get("expression").replaceWith(A.assignmentExpression("=",f,c.node.expression))}else c.replaceWith(A.returnStatement(c.node.expression))}}return this.node}this.replaceWith(e)}}function u(t){return this.resync(),Array.isArray(t)?Array.isArray(this.container)?(t=this._verifyNodeList(t),this._containerInsertAfter(t),this.remove()):this.replaceWithMultiple(t):this.replaceWith(t)}var p=s(54)["default"],c=s(85)["default"],l=s(86)["default"];e.__esModule=!0,e.replaceWithMultiple=i,e.replaceWithSourceString=r,e.replaceWith=n,e._replaceWith=a,e.replaceExpressionWithStatements=o,e.replaceInline=u;var h=s(245),f=c(h),d=s(201),y=c(d),m=s(208),v=c(m),g=s(258),x=s(41),A=l(x),b={Function:function(t){t.skip()},VariableDeclaration:function(t){if("var"===t.node.kind){var e=t.getBindingIdentifiers();for(var s in e)t.scope.push({id:e[s]});for(var i=[],r=t.node.declarations,n=Array.isArray(r),a=0,r=n?r:p(r);;){var o;if(n){if(a>=r.length)break;o=r[a++]}else{if(a=r.next(),a.done)break;o=a.value}var u=o;u.init&&i.push(A.expressionStatement(A.assignmentExpression("=",u.id,u.init)))}t.replaceWithMultiple(i)}}}},function(t,e,s){"use strict";function i(t){var e=l["default"].matchToToken(t);if("name"===e.type&&f["default"].keyword.isReservedWordES6(e.value))return"keyword";if("punctuator"===e.type)switch(e.value){case"{":case"}":return"curly";case"(":case")":return"parens";case"[":case"]":return"square"}return e.type}function r(t){return t.replace(l["default"],function(){for(var t=arguments.length,e=Array(t),s=0;t>s;s++)e[s]=arguments[s];var r=i(e),n=m[r];return n?e[0].split(v).map(function(t){return n(t)}).join("\n"):e[0]})}var n=s(85)["default"];e.__esModule=!0;var a=s(246),o=n(a),u=s(226),p=n(u),c=s(248),l=n(c),h=s(188),f=n(h),d=s(249),y=n(d),m={string:y["default"].red,punctuator:y["default"].bold,curly:y["default"].green,parens:y["default"].blue.bold,square:y["default"].yellow,keyword:y["default"].cyan,number:y["default"].magenta,regex:y["default"].magenta,comment:y["default"].grey,invalid:y["default"].inverse},v=/\r\n|[\n\r\u2028\u2029]/;e["default"]=function(t,e,s){var i=arguments.length<=3||void 0===arguments[3]?{}:arguments[3];s=Math.max(s,0);var n=i.highlightCode&&y["default"].supportsColor;n&&(t=r(t));var a=t.split(v),u=Math.max(e-3,0),c=Math.min(a.length,e+3);e||s||(u=0,c=a.length);var l=o["default"](a.slice(u,c),{start:u+1,before:" ",after:" | ",transform:function(t){t.number===e&&(s&&(t.line+="\n"+t.before+p["default"](" ",t.width)+t.after+p["default"](" ",s-1)+"^"),t.before=t.before.replace(/^./,">"))}}).join("\n");return n?y["default"].reset(l):l},t.exports=e["default"]},function(t,e,s){function i(t,e,s){return e in t?t[e]:s}function r(t,e){var s=i.bind(null,e||{}),r=s("transform",Function.prototype),a=s("padding"," "),o=s("before"," "),u=s("after"," | "),p=s("start",1),c=Array.isArray(t),l=c?t:t.split("\n"),h=p+l.length-1,f=String(h).length,d=l.map(function(t,e){var s=p+e,i={before:o,number:s,width:f,after:u,line:t};return r(i),i.before+n(i.number,f,a)+i.after+i.line});return c?d:d.join("\n")}var n=s(247);t.exports=r},function(t,e){function s(t,e,s){t=String(t);var i=-1;for(s||(s=" "),e-=t.length;++i<e;)t=s+t;return t}t.exports=s},function(t,e){t.exports=/((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|((?:0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?))|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]{1,6}\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-*\/%&|^]|<{1,2}|>{1,3}|!=?|={1,2})=?|[?:~]|[;,.[\](){}])|(\s+)|(^$|[\s\S])/g,t.exports.matchToToken=function(t){var e={type:"invalid",value:t[0]};return t[1]?(e.type="string",e.closed=!(!t[3]&&!t[4])):t[5]?e.type="comment":t[6]?(e.type="comment",e.closed=!!t[7]):t[8]?e.type="regex":t[9]?e.type="number":t[10]?e.type="name":t[11]?e.type="punctuator":t[12]&&(e.type="whitespace"),e}},function(t,e,s){(function(e){"use strict";function i(t){this.enabled=t&&void 0!==t.enabled?t.enabled:l}function r(t){var e=function(){return n.apply(e,arguments)};return e._styles=t,e.enabled=this.enabled,e.__proto__=y,e}function n(){var t=arguments,e=t.length,s=0!==e&&String(arguments[0]);if(e>1)for(var i=1;e>i;i++)s+=" "+t[i];if(!this.enabled||!s)return s;var r=this._styles,n=r.length,a=u.dim.open;for(!f||-1===r.indexOf("gray")&&-1===r.indexOf("grey")||(u.dim.open="");n--;){var o=u[r[n]];s=o.open+s.replace(o.closeRe,o.open)+o.close}return u.dim.open=a,s}function a(){var t={};return Object.keys(d).forEach(function(e){t[e]={get:function(){return r.call(this,[e])}}}),t}var o=s(250),u=s(251),p=s(253),c=s(255),l=s(257),h=Object.defineProperties,f="win32"===e.platform&&!/^xterm/i.test(e.env.TERM);f&&(u.blue.open="");var d=function(){var t={};return Object.keys(u).forEach(function(e){u[e].closeRe=new RegExp(o(u[e].close),"g"),t[e]={get:function(){return r.call(this,this._styles.concat(e))}}}),t}(),y=h(function(){},d);h(i.prototype,a()),t.exports=new i,t.exports.styles=u,t.exports.hasColor=c,t.exports.stripColor=p,t.exports.supportsColor=l}).call(e,s(206))},function(t,e){"use strict";var s=/[|\\{}()[\]^$+*?.]/g;t.exports=function(t){if("string"!=typeof t)throw new TypeError("Expected a string");return t.replace(s,"\\$&")}},function(t,e,s){(function(t){"use strict";function e(){var t={modifiers:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},colors:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39]},bgColors:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]}};return t.colors.grey=t.colors.gray,Object.keys(t).forEach(function(e){var s=t[e];Object.keys(s).forEach(function(e){var i=s[e];t[e]=s[e]={open:"["+i[0]+"m",close:"["+i[1]+"m"}}),Object.defineProperty(t,e,{value:s,enumerable:!1})}),t}Object.defineProperty(t,"exports",{enumerable:!0,get:e})}).call(e,s(252)(t))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children=[],t.webpackPolyfill=1),t}},function(t,e,s){"use strict";var i=s(254)();t.exports=function(t){return"string"==typeof t?t.replace(i,""):t}},function(t,e){"use strict";t.exports=function(){return/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g}},function(t,e,s){"use strict";var i=s(256),r=new RegExp(i().source);t.exports=r.test.bind(r)},function(t,e){"use strict";t.exports=function(){return/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g}},function(t,e,s){(function(e){"use strict";var s=e.argv,i=s.indexOf("--"),r=function(t){t="--"+t;var e=s.indexOf(t);return-1!==e&&(-1!==i?i>e:!0)};t.exports=function(){return"FORCE_COLOR"in e.env?!0:r("no-color")||r("no-colors")||r("color=false")?!1:r("color")||r("colors")||r("color=true")||r("color=always")?!0:e.stdout&&!e.stdout.isTTY?!1:"win32"===e.platform?!0:"COLORTERM"in e.env?!0:"dumb"===e.env.TERM?!1:/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(e.env.TERM)?!0:!1}()}).call(e,s(206))},function(t,e,s){var i,i;!function(e){t.exports=e()}(function(){return function t(e,s,r){function n(o,u){if(!s[o]){if(!e[o]){var p="function"==typeof i&&i;if(!u&&p)return i(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=s[o]={exports:{}};e[o][0].call(l.exports,function(t){var s=e[o][1][t];return n(s?s:t)},l,l.exports,t,e,s,r)}return s[o].exports}for(var a="function"==typeof i&&i,o=0;o<r.length;o++)n(r[o]);return n}({1:[function(t,e,s){"use strict";function i(t,e){return new a["default"](e,t).parse()}var r=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0,s.parse=i;var n=t("./parser"),a=r(n);t("./parser/util"),t("./parser/statement"),t("./parser/lval"),t("./parser/expression"),t("./parser/node"),t("./parser/location"),t("./parser/comments");var o=t("./tokenizer/types");t("./tokenizer"),t("./tokenizer/context");var u=t("./plugins/flow"),p=r(u),c=t("./plugins/jsx"),l=r(c);n.plugins.flow=p["default"],n.plugins.jsx=l["default"],s.tokTypes=o.types},{"./parser":5,"./parser/comments":3,"./parser/expression":4,"./parser/location":6,"./parser/lval":7,"./parser/node":8,"./parser/statement":9,"./parser/util":10,"./plugins/flow":11,"./plugins/jsx":12,"./tokenizer":15,"./tokenizer/context":14,"./tokenizer/types":17,"babel-runtime/helpers/interop-require-default":26}],2:[function(t,e,s){"use strict";function i(t){var e={};for(var s in r)e[s]=t&&s in t?t[s]:r[s];return e}s.__esModule=!0,s.getOptions=i;var r={sourceType:"script",allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,plugins:[],strictMode:null};s.defaultOptions=r},{}],3:[function(t,e,s){"use strict";function i(t){return t[t.length-1]}var r=t("babel-runtime/helpers/interop-require-default")["default"],n=t("./index"),a=r(n),o=a["default"].prototype;o.addComment=function(t){this.state.trailingComments.push(t),this.state.leadingComments.push(t)},o.processComment=function(t){if(!("Program"===t.type&&t.body.length>0)){var e=this.state.commentStack,s=void 0,r=void 0,n=void 0;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=t.end?(r=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else{var a=i(e);e.length>0&&a.trailingComments&&a.trailingComments[0].start>=t.end&&(r=a.trailingComments,a.trailingComments=null)}for(;e.length>0&&i(e).start>=t.start;)s=e.pop();if(s){if(s.leadingComments)if(s!==t&&i(s.leadingComments).end<=t.start)t.leadingComments=s.leadingComments,s.leadingComments=null;else for(n=s.leadingComments.length-2;n>=0;--n)if(s.leadingComments[n].end<=t.start){t.leadingComments=s.leadingComments.splice(0,n+1);break}}else if(this.state.leadingComments.length>0)if(i(this.state.leadingComments).end<=t.start)t.leadingComments=this.state.leadingComments,this.state.leadingComments=[];else{for(n=0;n<this.state.leadingComments.length&&!(this.state.leadingComments[n].end>t.start);n++);t.leadingComments=this.state.leadingComments.slice(0,n),0===t.leadingComments.length&&(t.leadingComments=null),r=this.state.leadingComments.slice(n),0===r.length&&(r=null)}r&&(r.length&&r[0].start>=t.start&&i(r).end<=t.end?t.innerComments=r:t.trailingComments=r),e.push(t)}}},{"./index":5,"babel-runtime/helpers/interop-require-default":26}],4:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/object/create")["default"],r=t("babel-runtime/core-js/get-iterator")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"],a=t("../tokenizer/types"),o=t("./index"),u=n(o),p=t("../util/identifier"),c=u["default"].prototype;c.checkPropClash=function(t,e){if(!t.computed){var s=t.key,i=void 0;switch(s.type){case"Identifier":i=s.name;break;case"StringLiteral":case"NumericLiteral":i=String(s.value);break;default:return}"__proto__"===i&&"init"===t.kind&&(e.proto&&this.raise(s.start,"Redefinition of __proto__ property"),e.proto=!0)}},c.parseExpression=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.parseMaybeAssign(t,e);if(this.match(a.types.comma)){var n=this.startNodeAt(s,i);for(n.expressions=[r];this.eat(a.types.comma);)n.expressions.push(this.parseMaybeAssign(t,e));return this.toReferencedList(n.expressions),this.finishNode(n,"SequenceExpression")}return r},c.parseMaybeAssign=function(t,e,s){if(this.match(a.types._yield)&&this.state.inGenerator)return this.parseYield();var i=void 0;e?i=!1:(e={start:0},i=!0);var r=this.state.start,n=this.state.startLoc;(this.match(a.types.parenL)||this.match(a.types.name))&&(this.state.potentialArrowAt=this.state.start);var o=this.parseMaybeConditional(t,e);if(s&&(o=s.call(this,o,r,n)),this.state.type.isAssign){var u=this.startNodeAt(r,n);if(u.operator=this.state.value,u.left=this.match(a.types.eq)?this.toAssignable(o):o,e.start=0,this.checkLVal(o),o.extra&&o.extra.parenthesized){var p=void 0;"ObjectPattern"===o.type?p="`({a}) = 0` use `({a} = 0)`":"ArrayPattern"===o.type&&(p="`([a]) = 0` use `([a] = 0)`"),p&&this.raise(o.start,"You're trying to assign to a parenthesized expression, eg. instead of "+p)}return this.next(),u.right=this.parseMaybeAssign(t),this.finishNode(u,"AssignmentExpression")}return i&&e.start&&this.unexpected(e.start),o},c.parseMaybeConditional=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.parseExprOps(t,e);if(e&&e.start)return r;if(this.eat(a.types.question)){var n=this.startNodeAt(s,i);return n.test=r,n.consequent=this.parseMaybeAssign(),this.expect(a.types.colon),n.alternate=this.parseMaybeAssign(t),this.finishNode(n,"ConditionalExpression")}return r},c.parseExprOps=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.parseMaybeUnary(e);return e&&e.start?r:this.parseExprOp(r,s,i,-1,t)},c.parseExprOp=function(t,e,s,i,r){var n=this.state.type.binop;if(!(null==n||r&&this.match(a.types._in))&&n>i){var o=this.startNodeAt(e,s);o.left=t,o.operator=this.state.value,"**"===o.operator&&"UnaryExpression"===t.type&&t.extra&&!t.extra.parenthesizedArgument&&this.raise(t.argument.start,"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");var u=this.state.type;this.next();var p=this.state.start,c=this.state.startLoc;return o.right=this.parseExprOp(this.parseMaybeUnary(),p,c,u.rightAssociative?n-1:n,r),this.finishNode(o,u===a.types.logicalOR||u===a.types.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(o,e,s,i,r)}return t},c.parseMaybeUnary=function(t){if(this.state.type.prefix){var e=this.startNode(),s=this.match(a.types.incDec);e.operator=this.state.value,e.prefix=!0,this.next();var i=this.state.type;return this.addExtra(e,"parenthesizedArgument",i===a.types.parenL),e.argument=this.parseMaybeUnary(),t&&t.start&&this.unexpected(t.start),s?this.checkLVal(e.argument):this.state.strict&&"delete"===e.operator&&"Identifier"===e.argument.type&&this.raise(e.start,"Deleting local variable in strict mode"), this.finishNode(e,s?"UpdateExpression":"UnaryExpression")}var r=this.state.start,n=this.state.startLoc,o=this.parseExprSubscripts(t);if(t&&t.start)return o;for(;this.state.type.postfix&&!this.canInsertSemicolon();){var e=this.startNodeAt(r,n);e.operator=this.state.value,e.prefix=!1,e.argument=o,this.checkLVal(o),this.next(),o=this.finishNode(e,"UpdateExpression")}return o},c.parseExprSubscripts=function(t){var e=this.state.start,s=this.state.startLoc,i=this.state.potentialArrowAt,r=this.parseExprAtom(t);return"ArrowFunctionExpression"===r.type&&r.start===i?r:t&&t.start?r:this.parseSubscripts(r,e,s)},c.parseSubscripts=function(t,e,s,i){for(;;){if(!i&&this.eat(a.types.doubleColon)){var r=this.startNodeAt(e,s);return r.object=t,r.callee=this.parseNoCallExpr(),this.parseSubscripts(this.finishNode(r,"BindExpression"),e,s,i)}if(this.eat(a.types.dot)){var r=this.startNodeAt(e,s);r.object=t,r.property=this.parseIdentifier(!0),r.computed=!1,t=this.finishNode(r,"MemberExpression")}else if(this.eat(a.types.bracketL)){var r=this.startNodeAt(e,s);r.object=t,r.property=this.parseExpression(),r.computed=!0,this.expect(a.types.bracketR),t=this.finishNode(r,"MemberExpression")}else if(!i&&this.match(a.types.parenL)){var n=this.state.potentialArrowAt===t.start&&"Identifier"===t.type&&"async"===t.name&&!this.canInsertSemicolon();this.next();var r=this.startNodeAt(e,s);if(r.callee=t,r.arguments=this.parseCallExpressionArguments(a.types.parenR,this.hasPlugin("trailingFunctionCommas"),n),t=this.finishNode(r,"CallExpression"),n&&this.shouldParseAsyncArrow())return this.parseAsyncArrowFromCallExpression(this.startNodeAt(e,s),r);this.toReferencedList(r.arguments)}else{if(!this.match(a.types.backQuote))return t;var r=this.startNodeAt(e,s);r.tag=t,r.quasi=this.parseTemplate(),t=this.finishNode(r,"TaggedTemplateExpression")}}},c.parseCallExpressionArguments=function(t,e,s){for(var i=void 0,r=[],n=!0;!this.eat(t);){if(n)n=!1;else if(this.expect(a.types.comma),e&&this.eat(t))break;this.match(a.types.parenL)&&!i&&(i=this.state.start),r.push(this.parseExprListItem())}return s&&i&&this.shouldParseAsyncArrow()&&this.unexpected(),r},c.shouldParseAsyncArrow=function(){return this.match(a.types.arrow)},c.parseAsyncArrowFromCallExpression=function(t,e){return this.hasPlugin("asyncFunctions")||this.unexpected(),this.expect(a.types.arrow),this.parseArrowExpression(t,e.arguments,!0)},c.parseNoCallExpr=function(){var t=this.state.start,e=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,e,!0)},c.parseExprAtom=function(t){var e=void 0,s=this.state.potentialArrowAt===this.state.start;switch(this.state.type){case a.types._super:return this.state.inMethod||this.options.allowSuperOutsideMethod||this.raise(this.state.start,"'super' outside of function or class"),e=this.startNode(),this.next(),this.match(a.types.parenL)||this.match(a.types.bracketL)||this.match(a.types.dot)||this.unexpected(),this.match(a.types.parenL)&&"constructor"!==this.state.inMethod&&!this.options.allowSuperOutsideMethod&&this.raise(e.start,"super() outside of class constructor"),this.finishNode(e,"Super");case a.types._this:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case a.types._yield:this.state.inGenerator&&this.unexpected();case a.types.name:e=this.startNode();var i=this.hasPlugin("asyncFunctions")&&"await"===this.state.value&&this.state.inAsync,r=this.shouldAllowYieldIdentifier(),n=this.parseIdentifier(i||r);if(this.hasPlugin("asyncFunctions"))if("await"===n.name){if(this.state.inAsync||this.inModule)return this.parseAwait(e)}else{if("async"===n.name&&this.match(a.types._function)&&!this.canInsertSemicolon())return this.next(),this.parseFunction(e,!1,!1,!0);if(s&&"async"===n.name&&this.match(a.types.name)){var o=[this.parseIdentifier()];return this.expect(a.types.arrow),this.parseArrowExpression(e,o,!0)}}return s&&!this.canInsertSemicolon()&&this.eat(a.types.arrow)?this.parseArrowExpression(e,[n]):n;case a.types._do:if(this.hasPlugin("doExpressions")){var u=this.startNode();this.next();var p=this.state.inFunction,c=this.state.labels;return this.state.labels=[],this.state.inFunction=!1,u.body=this.parseBlock(!1,!0),this.state.inFunction=p,this.state.labels=c,this.finishNode(u,"DoExpression")}case a.types.regexp:var l=this.state.value;return e=this.parseLiteral(l.value,"RegExpLiteral"),e.pattern=l.pattern,e.flags=l.flags,e;case a.types.num:return this.parseLiteral(this.state.value,"NumericLiteral");case a.types.string:return this.parseLiteral(this.state.value,"StringLiteral");case a.types._null:return e=this.startNode(),this.next(),this.finishNode(e,"NullLiteral");case a.types._true:case a.types._false:return e=this.startNode(),e.value=this.match(a.types._true),this.next(),this.finishNode(e,"BooleanLiteral");case a.types.parenL:return this.parseParenAndDistinguishExpression(null,null,s);case a.types.bracketL:return e=this.startNode(),this.next(),e.elements=this.parseExprList(a.types.bracketR,!0,!0,t),this.toReferencedList(e.elements),this.finishNode(e,"ArrayExpression");case a.types.braceL:return this.parseObj(!1,t);case a.types._function:return this.parseFunctionExpression();case a.types.at:this.parseDecorators();case a.types._class:return e=this.startNode(),this.takeDecorators(e),this.parseClass(e,!1);case a.types._new:return this.parseNew();case a.types.backQuote:return this.parseTemplate();case a.types.doubleColon:e=this.startNode(),this.next(),e.object=null;var h=e.callee=this.parseNoCallExpr();if("MemberExpression"===h.type)return this.finishNode(e,"BindExpression");this.raise(h.start,"Binding should be performed on object property.");default:this.unexpected()}},c.parseFunctionExpression=function(){var t=this.startNode(),e=this.parseIdentifier(!0);return this.state.inGenerator&&this.eat(a.types.dot)&&this.hasPlugin("functionSent")?this.parseMetaProperty(t,e,"sent"):this.parseFunction(t,!1)},c.parseMetaProperty=function(t,e,s){return t.meta=e,t.property=this.parseIdentifier(!0),t.property.name!==s&&this.raise(t.property.start,"The only valid meta property for new is "+e.name+"."+s),this.finishNode(t,"MetaProperty")},c.parseLiteral=function(t,e){var s=this.startNode();return this.addExtra(s,"rawValue",t),this.addExtra(s,"raw",this.input.slice(this.state.start,this.state.end)),s.value=t,this.next(),this.finishNode(s,e)},c.parseParenExpression=function(){this.expect(a.types.parenL);var t=this.parseExpression();return this.expect(a.types.parenR),t},c.parseParenAndDistinguishExpression=function(t,e,s,i){t=t||this.state.start,e=e||this.state.startLoc;var r=void 0;this.next();for(var n=this.state.start,o=this.state.startLoc,u=[],p=!0,c={start:0},l=void 0,h=void 0;!this.match(a.types.parenR);){if(p)p=!1;else if(this.expect(a.types.comma),this.match(a.types.parenR)&&this.hasPlugin("trailingFunctionCommas")){h=this.state.start;break}if(this.match(a.types.ellipsis)){var f=this.state.start,d=this.state.startLoc;l=this.state.start,u.push(this.parseParenItem(this.parseRest(),d,f));break}u.push(this.parseMaybeAssign(!1,c,this.parseParenItem))}var y=this.state.start,m=this.state.startLoc;if(this.expect(a.types.parenR),s&&!this.canInsertSemicolon()&&this.eat(a.types.arrow)){for(var v=0;v<u.length;v++){var g=u[v];g.extra&&g.extra.parenthesized&&this.unexpected(g.extra.parenStart)}return this.parseArrowExpression(this.startNodeAt(t,e),u,i)}if(!u.length){if(i)return;this.unexpected(this.state.lastTokStart)}return h&&this.unexpected(h),l&&this.unexpected(l),c.start&&this.unexpected(c.start),u.length>1?(r=this.startNodeAt(n,o),r.expressions=u,this.toReferencedList(r.expressions),this.finishNodeAt(r,"SequenceExpression",y,m)):r=u[0],this.addExtra(r,"parenthesized",!0),this.addExtra(r,"parenStart",t),r},c.parseParenItem=function(t){return t},c.parseNew=function(){var t=this.startNode(),e=this.parseIdentifier(!0);return this.eat(a.types.dot)?this.parseMetaProperty(t,e,"target"):(t.callee=this.parseNoCallExpr(),this.eat(a.types.parenL)?(t.arguments=this.parseExprList(a.types.parenR,this.hasPlugin("trailingFunctionCommas")),this.toReferencedList(t.arguments)):t.arguments=[],this.finishNode(t,"NewExpression"))},c.parseTemplateElement=function(){var t=this.startNode();return t.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),t.tail=this.match(a.types.backQuote),this.finishNode(t,"TemplateElement")},c.parseTemplate=function(){var t=this.startNode();this.next(),t.expressions=[];var e=this.parseTemplateElement();for(t.quasis=[e];!e.tail;)this.expect(a.types.dollarBraceL),t.expressions.push(this.parseExpression()),this.expect(a.types.braceR),t.quasis.push(e=this.parseTemplateElement());return this.next(),this.finishNode(t,"TemplateLiteral")},c.parseObj=function(t,e){var s=[],r=i(null),n=!0,o=this.startNode();for(o.properties=[],this.next();!this.eat(a.types.braceR);){if(n)n=!1;else if(this.expect(a.types.comma),this.eat(a.types.braceR))break;for(;this.match(a.types.at);)s.push(this.parseDecorator());var u=this.startNode(),p=!1,c=!1,l=void 0,h=void 0;if(s.length&&(u.decorators=s,s=[]),this.hasPlugin("objectRestSpread")&&this.match(a.types.ellipsis))u=this.parseSpread(),u.type=t?"RestProperty":"SpreadProperty",o.properties.push(u);else{if(u.method=!1,u.shorthand=!1,(t||e)&&(l=this.state.start,h=this.state.startLoc),t||(p=this.eat(a.types.star)),!t&&this.hasPlugin("asyncFunctions")&&this.isContextual("async")){p&&this.unexpected();var f=this.parseIdentifier();this.match(a.types.colon)||this.match(a.types.parenL)||this.match(a.types.braceR)?u.key=f:(c=!0,this.hasPlugin("asyncGenerators")&&(p=this.eat(a.types.star)),this.parsePropertyName(u))}else this.parsePropertyName(u);this.parseObjPropValue(u,l,h,p,c,t,e),this.checkPropClash(u,r),u.shorthand&&this.addExtra(u,"shorthand",!0),o.properties.push(u)}}return s.length&&this.raise(this.state.start,"You have trailing decorators with no property"),this.finishNode(o,t?"ObjectPattern":"ObjectExpression")},c.parseObjPropValue=function(t,e,s,i,r,n,o){if(r||i||this.match(a.types.parenL))return n&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,i,r),this.finishNode(t,"ObjectMethod");if(this.eat(a.types.colon))return t.value=n?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,o),this.finishNode(t,"ObjectProperty");if(!(t.computed||"Identifier"!==t.key.type||"get"!==t.key.name&&"set"!==t.key.name||this.match(a.types.comma)||this.match(a.types.braceR))){(i||r||n)&&this.unexpected(),t.kind=t.key.name,this.parsePropertyName(t),this.parseMethod(t,!1);var u="get"===t.kind?0:1;if(t.params.length!==u){var c=t.start;"get"===t.kind?this.raise(c,"getter should have no params"):this.raise(c,"setter should have exactly one param")}return this.finishNode(t,"ObjectMethod")}if(!t.computed&&"Identifier"===t.key.type){if(n){var l=this.isKeyword(t.key.name);!l&&this.state.strict&&(l=p.reservedWords.strictBind(t.key.name)||p.reservedWords.strict(t.key.name)),l&&this.raise(t.key.start,"Binding "+t.key.name),t.value=this.parseMaybeDefault(e,s,t.key.__clone())}else this.match(a.types.eq)&&o?(o.start||(o.start=this.state.start),t.value=this.parseMaybeDefault(e,s,t.key.__clone())):t.value=t.key.__clone();return t.shorthand=!0,this.finishNode(t,"ObjectProperty")}this.unexpected()},c.parsePropertyName=function(t){return this.eat(a.types.bracketL)?(t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(a.types.bracketR),t.key):(t.computed=!1,t.key=this.match(a.types.num)||this.match(a.types.string)?this.parseExprAtom():this.parseIdentifier(!0))},c.initFunction=function(t,e){t.id=null,t.generator=!1,t.expression=!1,this.hasPlugin("asyncFunctions")&&(t.async=!!e)},c.parseMethod=function(t,e,s){var i=this.state.inMethod;return this.state.inMethod=t.kind||!0,this.initFunction(t,s),this.expect(a.types.parenL),t.params=this.parseBindingList(a.types.parenR,!1,this.hasPlugin("trailingFunctionCommas")),t.generator=e,this.parseFunctionBody(t),this.state.inMethod=i,t},c.parseArrowExpression=function(t,e,s){return this.initFunction(t,s),t.params=this.toAssignableList(e,!0),this.parseFunctionBody(t,!0),this.finishNode(t,"ArrowFunctionExpression")},c.parseFunctionBody=function(t,e){var s=e&&!this.match(a.types.braceL),n=this.state.inAsync;if(this.state.inAsync=t.async,s)t.body=this.parseMaybeAssign(),t.expression=!0;else{var o=this.state.inFunction,u=this.state.inGenerator,p=this.state.labels;this.state.inFunction=!0,this.state.inGenerator=t.generator,this.state.labels=[],t.body=this.parseBlock(!0),t.expression=!1,this.state.inFunction=o,this.state.inGenerator=u,this.state.labels=p}this.state.inAsync=n;var c=this.state.strict,l=!1,h=!1;if(e&&(c=!0),!s&&t.body.directives.length)for(var f=t.body.directives,d=Array.isArray(f),y=0,f=d?f:r(f);;){var m;if(d){if(y>=f.length)break;m=f[y++]}else{if(y=f.next(),y.done)break;m=y.value}var v=m;if("use strict"===v.value.value){h=!0,c=!0,l=!0;break}}if(h&&t.id&&"Identifier"===t.id.type&&"yield"===t.id.name&&this.raise(t.id.start,"Binding yield in strict mode"),c){var g=i(null),x=this.state.strict;l&&(this.state.strict=!0),t.id&&this.checkLVal(t.id,!0);for(var A=t.params,b=Array.isArray(A),E=0,A=b?A:r(A);;){var C;if(b){if(E>=A.length)break;C=A[E++]}else{if(E=A.next(),E.done)break;C=E.value}var D=C;this.checkLVal(D,!0,g)}this.state.strict=x}},c.parseExprList=function(t,e,s,i){for(var r=[],n=!0;!this.eat(t);){if(n)n=!1;else if(this.expect(a.types.comma),e&&this.eat(t))break;r.push(this.parseExprListItem(s,i))}return r},c.parseExprListItem=function(t,e){var s=void 0;return s=t&&this.match(a.types.comma)?null:this.match(a.types.ellipsis)?this.parseSpread(e):this.parseMaybeAssign(!1,e)},c.parseIdentifier=function(t){var e=this.startNode();return this.match(a.types.name)?(!t&&this.state.strict&&p.reservedWords.strict(this.state.value)&&this.raise(this.state.start,"The keyword '"+this.state.value+"' is reserved"),e.name=this.state.value):t&&this.state.type.keyword?e.name=this.state.type.keyword:this.unexpected(),!t&&"await"===e.name&&this.state.inAsync&&this.raise(e.start,"invalid use of await inside of an async function"),this.next(),this.finishNode(e,"Identifier")},c.parseAwait=function(t){return this.state.inAsync||this.unexpected(),this.isLineTerminator()&&this.unexpected(),this.match(a.types.star)&&this.raise(t.start,"await* has been removed from the async functions proposal. Use Promise.all() instead."),t.argument=this.parseMaybeUnary(),this.finishNode(t,"AwaitExpression")},c.parseYield=function(){var t=this.startNode();return this.next(),this.match(a.types.semi)||this.canInsertSemicolon()||!this.match(a.types.star)&&!this.state.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(a.types.star),t.argument=this.parseMaybeAssign()),this.finishNode(t,"YieldExpression")}},{"../tokenizer/types":17,"../util/identifier":18,"./index":5,"babel-runtime/core-js/get-iterator":21,"babel-runtime/core-js/object/create":22,"babel-runtime/helpers/interop-require-default":26}],5:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/inherits")["default"],r=t("babel-runtime/helpers/class-call-check")["default"],n=t("babel-runtime/core-js/get-iterator")["default"],a=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var o=t("../util/identifier"),u=t("../options"),p=t("../tokenizer"),c=a(p),l={};s.plugins=l;var h=function(t){function e(s,i){r(this,e),s=u.getOptions(s),t.call(this,s,i),this.options=s,this.inModule="module"===this.options.sourceType,this.isReservedWord=o.reservedWords[6],this.input=i,this.plugins=this.loadPlugins(this.options.plugins),0===this.state.pos&&"#"===this.input[0]&&"!"===this.input[1]&&this.skipLineComment(2)}return i(e,t),e.prototype.hasPlugin=function(t){return!(!this.plugins["*"]&&!this.plugins[t])},e.prototype.extend=function(t,e){this[t]=e(this[t])},e.prototype.loadPlugins=function(t){var e={};t.indexOf("flow")>=0&&(t=t.filter(function(t){return"flow"!==t}),t.push("flow"));for(var i=t,r=Array.isArray(i),a=0,i=r?i:n(i);;){var o;if(r){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;if(!e[u]){e[u]=!0;var p=s.plugins[u];p&&p(this)}}return e},e.prototype.parse=function(){var t=this.startNode(),e=this.startNode();return this.nextToken(),this.parseTopLevel(t,e)},e}(c["default"]);s["default"]=h},{"../options":2,"../tokenizer":15,"../util/identifier":18,"babel-runtime/core-js/get-iterator":21,"babel-runtime/helpers/class-call-check":24,"babel-runtime/helpers/inherits":25,"babel-runtime/helpers/interop-require-default":26}],6:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../util/location"),n=t("./index"),a=i(n),o=a["default"].prototype;o.raise=function(t,e){var s=r.getLineInfo(this.input,t);e+=" ("+s.line+":"+s.column+")";var i=new SyntaxError(e);throw i.pos=t,i.loc=s,i}},{"../util/location":19,"./index":5,"babel-runtime/helpers/interop-require-default":26}],7:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/get-iterator")["default"],r=t("babel-runtime/helpers/interop-require-default")["default"],n=t("../tokenizer/types"),a=t("./index"),o=r(a),u=t("../util/identifier"),p=o["default"].prototype;p.toAssignable=function(t,e){if(t)switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":t.type="ObjectPattern";for(var s=t.properties,r=Array.isArray(s),n=0,s=r?s:i(s);;){var a;if(r){if(n>=s.length)break;a=s[n++]}else{if(n=s.next(),n.done)break;a=n.value}var o=a;"ObjectMethod"===o.type?"get"===o.kind||"set"===o.kind?this.raise(o.key.start,"Object pattern can't contain getter or setter"):this.raise(o.key.start,"Object pattern can't contain methods"):this.toAssignable(o,e)}break;case"ObjectProperty":this.toAssignable(t.value,e);break;case"SpreadProperty":t.type="RestProperty";break;case"ArrayExpression":t.type="ArrayPattern",this.toAssignableList(t.elements,e);break;case"AssignmentExpression":"="===t.operator?(t.type="AssignmentPattern",delete t.operator):this.raise(t.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!e)break;default:this.raise(t.start,"Assigning to rvalue")}return t},p.toAssignableList=function(t,e){var s=t.length;if(s){var i=t[s-1];if(i&&"RestElement"===i.type)--s;else if(i&&"SpreadElement"===i.type){i.type="RestElement";var r=i.argument;this.toAssignable(r,e),"Identifier"!==r.type&&"MemberExpression"!==r.type&&"ArrayPattern"!==r.type&&this.unexpected(r.start),--s}}for(var n=0;s>n;n++){var a=t[n];a&&this.toAssignable(a,e)}return t},p.toReferencedList=function(t){return t},p.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(t),this.finishNode(e,"SpreadElement")},p.parseRest=function(){var t=this.startNode();return this.next(),t.argument=this.parseBindingIdentifier(),this.finishNode(t,"RestElement")},p.shouldAllowYieldIdentifier=function(){return this.match(n.types._yield)&&!this.state.strict&&!this.state.inGenerator},p.parseBindingIdentifier=function(){return this.parseIdentifier(this.shouldAllowYieldIdentifier())},p.parseBindingAtom=function(){switch(this.state.type){case n.types._yield:(this.state.strict||this.state.inGenerator)&&this.unexpected();case n.types.name:return this.parseIdentifier(!0);case n.types.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(n.types.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case n.types.braceL:return this.parseObj(!0);default:this.unexpected()}},p.parseBindingList=function(t,e,s){for(var i=[],r=!0;!this.eat(t);)if(r?r=!1:this.expect(n.types.comma),e&&this.match(n.types.comma))i.push(null);else{if(s&&this.eat(t))break;if(this.match(n.types.ellipsis)){i.push(this.parseAssignableListItemTypes(this.parseRest())),this.expect(t);break}var a=this.parseMaybeDefault();this.parseAssignableListItemTypes(a),i.push(this.parseMaybeDefault(null,null,a))}return i},p.parseAssignableListItemTypes=function(t){return t},p.parseMaybeDefault=function(t,e,s){if(e=e||this.state.startLoc,t=t||this.state.start,s=s||this.parseBindingAtom(),!this.eat(n.types.eq))return s;var i=this.startNodeAt(t,e);return i.left=s,i.right=this.parseMaybeAssign(),this.finishNode(i,"AssignmentPattern")},p.checkLVal=function(t,e,s){switch(t.type){case"Identifier":if(this.state.strict&&(u.reservedWords.strictBind(t.name)||u.reservedWords.strict(t.name))&&this.raise(t.start,(e?"Binding ":"Assigning to ")+t.name+" in strict mode"),s){var r="_"+t.name;s[r]?this.raise(t.start,"Argument name clash in strict mode"):s[r]=!0}break;case"MemberExpression":e&&this.raise(t.start,(e?"Binding":"Assigning to")+" member expression");break;case"ObjectPattern":for(var n=t.properties,a=Array.isArray(n),o=0,n=a?n:i(n);;){var p;if(a){if(o>=n.length)break;p=n[o++]}else{if(o=n.next(),o.done)break;p=o.value}var c=p;"ObjectProperty"===c.type&&(c=c.value),this.checkLVal(c,e,s)}break;case"ArrayPattern":for(var l=t.elements,h=Array.isArray(l),f=0,l=h?l:i(l);;){var d;if(h){if(f>=l.length)break;d=l[f++]}else{if(f=l.next(),f.done)break;d=f.value}var y=d;y&&this.checkLVal(y,e,s)}break;case"AssignmentPattern":this.checkLVal(t.left,e,s);break;case"RestProperty":case"RestElement":this.checkLVal(t.argument,e,s);break;default:this.raise(t.start,(e?"Binding":"Assigning to")+" rvalue")}}},{"../tokenizer/types":17,"../util/identifier":18,"./index":5,"babel-runtime/core-js/get-iterator":21,"babel-runtime/helpers/interop-require-default":26}],8:[function(t,e,s){"use strict";function i(t,e,s,i){return t.type=e,t.end=s,t.loc.end=i,this.processComment(t),t}var r=t("babel-runtime/helpers/class-call-check")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"],a=t("./index"),o=n(a),u=t("../util/location"),p=o["default"].prototype,c=function(){function t(e,s){r(this,t),this.type="",this.start=e,this.end=0,this.loc=new u.SourceLocation(s)}return t.prototype.__clone=function(){var e=new t;for(var s in this)e[s]=this[s];return e},t}();p.startNode=function(){return new c(this.state.start,this.state.startLoc)},p.startNodeAt=function(t,e){return new c(t,e)},p.finishNode=function(t,e){return i.call(this,t,e,this.state.lastTokEnd,this.state.lastTokEndLoc)},p.finishNodeAt=function(t,e,s,r){return i.call(this,t,e,s,r)}},{"../util/location":19,"./index":5,"babel-runtime/helpers/class-call-check":24,"babel-runtime/helpers/interop-require-default":26}],9:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/object/create")["default"],r=t("babel-runtime/core-js/get-iterator")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"],a=t("../tokenizer/types"),o=t("./index"),u=n(o),p=t("../util/whitespace"),c=u["default"].prototype;c.parseTopLevel=function(t,e){return e.sourceType=this.options.sourceType,this.parseBlockBody(e,!0,!0,a.types.eof),t.program=this.finishNode(e,"Program"),t.comments=this.state.comments,t.tokens=this.state.tokens,this.finishNode(t,"File")};var l={kind:"loop"},h={kind:"switch"};c.stmtToDirective=function(t){var e=t.expression,s=this.startNodeAt(e.start,e.loc.start),i=this.startNodeAt(t.start,t.loc.start),r=this.input.slice(e.start,e.end),n=s.value=r.slice(1,-1);return this.addExtra(s,"raw",r),this.addExtra(s,"rawValue",n),i.value=this.finishNodeAt(s,"DirectiveLiteral",e.end,e.loc.end),this.finishNodeAt(i,"Directive",t.end,t.loc.end)},c.parseStatement=function(t,e){this.match(a.types.at)&&this.parseDecorators(!0);var s=this.state.type,i=this.startNode();switch(s){case a.types._break:case a.types._continue:return this.parseBreakContinueStatement(i,s.keyword);case a.types._debugger:return this.parseDebuggerStatement(i);case a.types._do:return this.parseDoStatement(i);case a.types._for:return this.parseForStatement(i);case a.types._function:return t||this.unexpected(),this.parseFunctionStatement(i);case a.types._class:return t||this.unexpected(),this.takeDecorators(i),this.parseClass(i,!0);case a.types._if:return this.parseIfStatement(i);case a.types._return:return this.parseReturnStatement(i);case a.types._switch:return this.parseSwitchStatement(i);case a.types._throw:return this.parseThrowStatement(i);case a.types._try:return this.parseTryStatement(i);case a.types._let:case a.types._const:t||this.unexpected();case a.types._var:return this.parseVarStatement(i,s);case a.types._while:return this.parseWhileStatement(i);case a.types._with:return this.parseWithStatement(i);case a.types.braceL:return this.parseBlock();case a.types.semi:return this.parseEmptyStatement(i);case a.types._export:case a.types._import:return this.options.allowImportExportEverywhere||(e||this.raise(this.state.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.state.start,"'import' and 'export' may appear only with 'sourceType: module'")),s===a.types._import?this.parseImport(i):this.parseExport(i);case a.types.name:if(this.hasPlugin("asyncFunctions")&&"async"===this.state.value){var r=this.state.clone();if(this.next(),this.match(a.types._function)&&!this.canInsertSemicolon())return this.expect(a.types._function),this.parseFunction(i,!0,!1,!0);this.state=r}}var n=this.state.value,o=this.parseExpression();return s===a.types.name&&"Identifier"===o.type&&this.eat(a.types.colon)?this.parseLabeledStatement(i,n,o):this.parseExpressionStatement(i,o)},c.takeDecorators=function(t){this.state.decorators.length&&(t.decorators=this.state.decorators,this.state.decorators=[])},c.parseDecorators=function(t){for(;this.match(a.types.at);)this.state.decorators.push(this.parseDecorator());t&&this.match(a.types._export)||this.match(a.types._class)||this.raise(this.state.start,"Leading decorators must be attached to a class declaration")},c.parseDecorator=function(){this.hasPlugin("decorators")||this.unexpected();var t=this.startNode();return this.next(),t.expression=this.parseMaybeAssign(),this.finishNode(t,"Decorator")},c.parseBreakContinueStatement=function(t,e){var s="break"===e;this.next(),this.isLineTerminator()?t.label=null:this.match(a.types.name)?(t.label=this.parseIdentifier(),this.semicolon()):this.unexpected();var i=void 0;for(i=0;i<this.state.labels.length;++i){var r=this.state.labels[i];if(null==t.label||r.name===t.label.name){if(null!=r.kind&&(s||"loop"===r.kind))break;if(t.label&&s)break}}return i===this.state.labels.length&&this.raise(t.start,"Unsyntactic "+e),this.finishNode(t,s?"BreakStatement":"ContinueStatement")},c.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")},c.parseDoStatement=function(t){return this.next(),this.state.labels.push(l),t.body=this.parseStatement(!1),this.state.labels.pop(),this.expect(a.types._while),t.test=this.parseParenExpression(),this.eat(a.types.semi),this.finishNode(t,"DoWhileStatement")},c.parseForStatement=function(t){if(this.next(),this.state.labels.push(l),this.expect(a.types.parenL),this.match(a.types.semi))return this.parseFor(t,null);if(this.match(a.types._var)||this.match(a.types._let)||this.match(a.types._const)){var e=this.startNode(),s=this.state.type;return this.next(),this.parseVar(e,!0,s),this.finishNode(e,"VariableDeclaration"),!this.match(a.types._in)&&!this.isContextual("of")||1!==e.declarations.length||e.declarations[0].init?this.parseFor(t,e):this.parseForIn(t,e)}var i={start:0},r=this.parseExpression(!0,i);return this.match(a.types._in)||this.isContextual("of")?(this.toAssignable(r),this.checkLVal(r),this.parseForIn(t,r)):(i.start&&this.unexpected(i.start),this.parseFor(t,r))},c.parseFunctionStatement=function(t){return this.next(),this.parseFunction(t,!0)},c.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement(!1),t.alternate=this.eat(a.types._else)?this.parseStatement(!1):null,this.finishNode(t,"IfStatement")},c.parseReturnStatement=function(t){return this.state.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.state.start,"'return' outside of function"),this.next(),this.isLineTerminator()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")},c.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(a.types.braceL),this.state.labels.push(h);for(var e=void 0,s=void 0;!this.match(a.types.braceR);)if(this.match(a.types._case)||this.match(a.types._default)){var i=this.match(a.types._case);e&&this.finishNode(e,"SwitchCase"),t.cases.push(e=this.startNode()),e.consequent=[],this.next(),i?e.test=this.parseExpression():(s&&this.raise(this.state.lastTokStart,"Multiple default clauses"),s=!0,e.test=null),this.expect(a.types.colon)}else e?e.consequent.push(this.parseStatement(!0)):this.unexpected();return e&&this.finishNode(e,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")},c.parseThrowStatement=function(t){return this.next(),p.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.start))&&this.raise(this.state.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")};var f=[];c.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.match(a.types._catch)){var e=this.startNode();this.next(),this.expect(a.types.parenL),e.param=this.parseBindingAtom(),this.checkLVal(e.param,!0,i(null)),this.expect(a.types.parenR),e.body=this.parseBlock(),t.handler=this.finishNode(e,"CatchClause")}return t.guardedHandlers=f,t.finalizer=this.eat(a.types._finally)?this.parseBlock():null,t.handler||t.finalizer||this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")},c.parseVarStatement=function(t,e){return this.next(),this.parseVar(t,!1,e),this.semicolon(),this.finishNode(t,"VariableDeclaration")},c.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.state.labels.push(l),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,"WhileStatement")},c.parseWithStatement=function(t){return this.state.strict&&this.raise(this.state.start,"'with' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement(!1),this.finishNode(t,"WithStatement")},c.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")},c.parseLabeledStatement=function(t,e,s){for(var i=this.state.labels,n=Array.isArray(i),o=0,i=n?i:r(i);;){var u;if(n){if(o>=i.length)break;u=i[o++]}else{if(o=i.next(),o.done)break;u=o.value}var p=u;p.name===e&&this.raise(s.start,"Label '"+e+"' is already declared")}for(var c=this.state.type.isLoop?"loop":this.match(a.types._switch)?"switch":null,l=this.state.labels.length-1;l>=0;l--){var p=this.state.labels[l];if(p.statementStart!==t.start)break;p.statementStart=this.state.start,p.kind=c}return this.state.labels.push({name:e,kind:c,statementStart:this.state.start}),t.body=this.parseStatement(!0),this.state.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")},c.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")},c.parseBlock=function(t){var e=this.startNode();return this.expect(a.types.braceL),this.parseBlockBody(e,t,!1,a.types.braceR),this.finishNode(e,"BlockStatement")},c.parseBlockBody=function(t,e,s,i){t.body=[],t.directives=[];for(var r=!1,n=void 0,a=void 0;!this.eat(i);){r||!this.state.containsOctal||a||(a=this.state.octalPosition);var o=this.parseStatement(!0,s);if(!e||r||"ExpressionStatement"!==o.type||"StringLiteral"!==o.expression.type||o.expression.extra.parenthesized)r=!0,t.body.push(o);else{var u=this.stmtToDirective(o);t.directives.push(u),void 0===n&&"use strict"===u.value.value&&(n=this.state.strict,this.setStrict(!0),a&&this.raise(a,"Octal literal in strict mode"))}}n===!1&&this.setStrict(!1)},c.parseFor=function(t,e){return t.init=e,this.expect(a.types.semi),t.test=this.match(a.types.semi)?null:this.parseExpression(),this.expect(a.types.semi),t.update=this.match(a.types.parenR)?null:this.parseExpression(), this.expect(a.types.parenR),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,"ForStatement")},c.parseForIn=function(t,e){var s=this.match(a.types._in)?"ForInStatement":"ForOfStatement";return this.next(),t.left=e,t.right=this.parseExpression(),this.expect(a.types.parenR),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,s)},c.parseVar=function(t,e,s){for(t.declarations=[],t.kind=s.keyword;;){var i=this.startNode();if(this.parseVarHead(i),this.eat(a.types.eq)?i.init=this.parseMaybeAssign(e):s!==a.types._const||this.match(a.types._in)||this.isContextual("of")?"Identifier"===i.id.type||e&&(this.match(a.types._in)||this.isContextual("of"))?i.init=null:this.raise(this.state.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),t.declarations.push(this.finishNode(i,"VariableDeclarator")),!this.eat(a.types.comma))break}return t},c.parseVarHead=function(t){t.id=this.parseBindingAtom(),this.checkLVal(t.id,!0)},c.parseFunction=function(t,e,s,i,r){var n=this.state.inMethod;return this.state.inMethod=!1,this.initFunction(t,i),this.match(a.types.star)&&(t.async&&!this.hasPlugin("asyncGenerators")?this.unexpected():(t.generator=!0,this.next())),!e||r||this.match(a.types.name)||this.match(a.types._yield)||this.unexpected(),(this.match(a.types.name)||this.match(a.types._yield))&&(t.id=this.parseBindingIdentifier()),this.parseFunctionParams(t),this.parseFunctionBody(t,s),this.state.inMethod=n,this.finishNode(t,e?"FunctionDeclaration":"FunctionExpression")},c.parseFunctionParams=function(t){this.expect(a.types.parenL),t.params=this.parseBindingList(a.types.parenR,!1,this.hasPlugin("trailingFunctionCommas"))},c.parseClass=function(t,e,s){return this.next(),this.parseClassId(t,e,s),this.parseClassSuper(t),this.parseClassBody(t),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")},c.isClassProperty=function(){return this.match(a.types.eq)||this.match(a.types.semi)||this.canInsertSemicolon()},c.parseClassBody=function(t){var e=this.state.strict;this.state.strict=!0;var s=!1,i=!1,r=[],n=this.startNode();for(n.body=[],this.expect(a.types.braceL);!this.eat(a.types.braceR);)if(!this.eat(a.types.semi))if(this.match(a.types.at))r.push(this.parseDecorator());else{var o=this.startNode();r.length&&(o.decorators=r,r=[]);var u=!1,p=this.match(a.types.name)&&"static"===this.state.value,c=this.eat(a.types.star),l=!1,h=!1;if(this.parsePropertyName(o),o["static"]=p&&!this.match(a.types.parenL),o["static"]&&(c&&this.unexpected(),c=this.eat(a.types.star),this.parsePropertyName(o)),!c&&"Identifier"===o.key.type&&!o.computed){if(this.isClassProperty()){n.body.push(this.parseClassProperty(o));continue}this.hasPlugin("classConstructorCall")&&"call"===o.key.name&&this.match(a.types.name)&&"constructor"===this.state.value&&(u=!0,this.parsePropertyName(o))}var f=this.hasPlugin("asyncFunctions")&&!this.match(a.types.parenL)&&!o.computed&&"Identifier"===o.key.type&&"async"===o.key.name;if(f&&(this.hasPlugin("asyncGenerators")&&this.eat(a.types.star)&&(c=!0),h=!0,this.parsePropertyName(o)),o.kind="method",!o.computed){var d=o.key;h||c||"Identifier"!==d.type||this.match(a.types.parenL)||"get"!==d.name&&"set"!==d.name||(l=!0,o.kind=d.name,d=this.parsePropertyName(o));var y=!u&&!o["static"]&&("Identifier"===d.type&&"constructor"===d.name||"StringLiteral"===d.type&&"constructor"===d.value);y&&(i&&this.raise(d.start,"Duplicate constructor in the same class"),l&&this.raise(d.start,"Constructor can't have get/set modifier"),c&&this.raise(d.start,"Constructor can't be a generator"),h&&this.raise(d.start,"Constructor can't be an async function"),o.kind="constructor",i=!0);var m=o["static"]&&("Identifier"===d.type&&"prototype"===d.name||"StringLiteral"===d.type&&"prototype"===d.value);m&&this.raise(d.start,"Classes may not have static property named prototype")}if(u&&(s&&this.raise(o.start,"Duplicate constructor call in the same class"),o.kind="constructorCall",s=!0),"constructor"!==o.kind&&"constructorCall"!==o.kind||!o.decorators||this.raise(o.start,"You can't attach decorators to a class constructor"),this.parseClassMethod(n,o,c,h),l){var v="get"===o.kind?0:1;if(o.params.length!==v){var g=o.start;"get"===o.kind?this.raise(g,"getter should have no params"):this.raise(g,"setter should have exactly one param")}}}r.length&&this.raise(this.state.start,"You have trailing decorators with no method"),t.body=this.finishNode(n,"ClassBody"),this.state.strict=e},c.parseClassProperty=function(t){return this.match(a.types.eq)?(this.hasPlugin("classProperties")||this.unexpected(),this.next(),t.value=this.parseMaybeAssign()):t.value=null,this.eat(a.types.semi)||this.raise(t.value&&t.value.end||t.key.end,"A semicolon is required after a class property"),this.finishNode(t,"ClassProperty")},c.parseClassMethod=function(t,e,s,i){this.parseMethod(e,s,i),t.body.push(this.finishNode(e,"ClassMethod"))},c.parseClassId=function(t,e,s){this.match(a.types.name)?t.id=this.parseIdentifier():s||!e?t.id=null:this.unexpected()},c.parseClassSuper=function(t){t.superClass=this.eat(a.types._extends)?this.parseExprSubscripts():null},c.parseExport=function(t){if(this.next(),this.match(a.types.star)){var e=this.startNode();if(this.next(),!this.hasPlugin("exportExtensions")||!this.eatContextual("as"))return this.parseExportFrom(t,!0),this.finishNode(t,"ExportAllDeclaration");e.exported=this.parseIdentifier(),t.specifiers=[this.finishNode(e,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(t),this.parseExportFrom(t,!0)}else if(this.hasPlugin("exportExtensions")&&this.isExportDefaultSpecifier()){var e=this.startNode();if(e.exported=this.parseIdentifier(!0),t.specifiers=[this.finishNode(e,"ExportDefaultSpecifier")],this.match(a.types.comma)&&this.lookahead().type===a.types.star){this.expect(a.types.comma);var s=this.startNode();this.expect(a.types.star),this.expectContextual("as"),s.exported=this.parseIdentifier(),t.specifiers.push(this.finishNode(s,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(t);this.parseExportFrom(t,!0)}else{if(this.eat(a.types._default)){var i=this.startNode(),r=!1;return this.eat(a.types._function)?i=this.parseFunction(i,!0,!1,!1,!0):this.match(a.types._class)?i=this.parseClass(i,!0,!0):(r=!0,i=this.parseMaybeAssign()),t.declaration=i,r&&this.semicolon(),this.checkExport(t),this.finishNode(t,"ExportDefaultDeclaration")}this.state.type.keyword||this.shouldParseExportDeclaration()?(t.specifiers=[],t.source=null,t.declaration=this.parseExportDeclaration(t)):(t.declaration=null,t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t))}return this.checkExport(t),this.finishNode(t,"ExportNamedDeclaration")},c.parseExportDeclaration=function(){return this.parseStatement(!0)},c.isExportDefaultSpecifier=function(){if(this.match(a.types.name))return"type"!==this.state.value&&"async"!==this.state.value&&"interface"!==this.state.value;if(!this.match(a.types._default))return!1;var t=this.lookahead();return t.type===a.types.comma||t.type===a.types.name&&"from"===t.value},c.parseExportSpecifiersMaybe=function(t){this.eat(a.types.comma)&&(t.specifiers=t.specifiers.concat(this.parseExportSpecifiers()))},c.parseExportFrom=function(t,e){this.eatContextual("from")?(t.source=this.match(a.types.string)?this.parseExprAtom():this.unexpected(),this.checkExport(t)):e?this.unexpected():t.source=null,this.semicolon()},c.shouldParseExportDeclaration=function(){return this.hasPlugin("asyncFunctions")&&this.isContextual("async")},c.checkExport=function(t){if(this.state.decorators.length){var e=t.declaration&&("ClassDeclaration"===t.declaration.type||"ClassExpression"===t.declaration.type);t.declaration&&e||this.raise(t.start,"You can only use decorators on an export when exporting a class"),this.takeDecorators(t.declaration)}},c.parseExportSpecifiers=function(){var t=[],e=!0,s=void 0;for(this.expect(a.types.braceL);!this.eat(a.types.braceR);){if(e)e=!1;else if(this.expect(a.types.comma),this.eat(a.types.braceR))break;var i=this.match(a.types._default);i&&!s&&(s=!0);var r=this.startNode();r.local=this.parseIdentifier(i),r.exported=this.eatContextual("as")?this.parseIdentifier(!0):r.local.__clone(),t.push(this.finishNode(r,"ExportSpecifier"))}return s&&!this.isContextual("from")&&this.unexpected(),t},c.parseImport=function(t){return this.next(),this.match(a.types.string)?(t.specifiers=[],t.source=this.parseExprAtom()):(t.specifiers=[],this.parseImportSpecifiers(t),this.expectContextual("from"),t.source=this.match(a.types.string)?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(t,"ImportDeclaration")},c.parseImportSpecifiers=function(t){var e=!0;if(this.match(a.types.name)){var s=this.state.start,i=this.state.startLoc;if(t.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(),s,i)),!this.eat(a.types.comma))return}if(this.match(a.types.star)){var r=this.startNode();return this.next(),this.expectContextual("as"),r.local=this.parseIdentifier(),this.checkLVal(r.local,!0),void t.specifiers.push(this.finishNode(r,"ImportNamespaceSpecifier"))}for(this.expect(a.types.braceL);!this.eat(a.types.braceR);){if(e)e=!1;else if(this.expect(a.types.comma),this.eat(a.types.braceR))break;var r=this.startNode();r.imported=this.parseIdentifier(!0),r.local=this.eatContextual("as")?this.parseIdentifier():r.imported.__clone(),this.checkLVal(r.local,!0),t.specifiers.push(this.finishNode(r,"ImportSpecifier"))}},c.parseImportSpecifierDefault=function(t,e,s){var i=this.startNodeAt(e,s);return i.local=t,this.checkLVal(i.local,!0),this.finishNode(i,"ImportDefaultSpecifier")}},{"../tokenizer/types":17,"../util/whitespace":20,"./index":5,"babel-runtime/core-js/get-iterator":21,"babel-runtime/core-js/object/create":22,"babel-runtime/helpers/interop-require-default":26}],10:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"],r=t("../tokenizer/types"),n=t("./index"),a=i(n),o=t("../util/whitespace"),u=a["default"].prototype;u.addExtra=function(t,e,s){if(t){var i=t.extra=t.extra||{};i[e]=s}},u.isRelational=function(t){return this.match(r.types.relational)&&this.state.value===t},u.expectRelational=function(t){this.isRelational(t)?this.next():this.unexpected()},u.isContextual=function(t){return this.match(r.types.name)&&this.state.value===t},u.eatContextual=function(t){return this.state.value===t&&this.eat(r.types.name)},u.expectContextual=function(t){this.eatContextual(t)||this.unexpected()},u.canInsertSemicolon=function(){return this.match(r.types.eof)||this.match(r.types.braceR)||o.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.start))},u.isLineTerminator=function(){return this.eat(r.types.semi)||this.canInsertSemicolon()},u.semicolon=function(){this.isLineTerminator()||this.unexpected()},u.expect=function(t){return this.eat(t)||this.unexpected()},u.unexpected=function(t){this.raise(null!=t?t:this.state.start,"Unexpected token")}},{"../tokenizer/types":17,"../util/whitespace":20,"./index":5,"babel-runtime/helpers/interop-require-default":26}],11:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var r=t("../tokenizer/types"),n=t("../parser"),a=i(n),o=a["default"].prototype;o.flowParseTypeInitialiser=function(t){var e=this.state.inType;this.state.inType=!0,this.expect(t||r.types.colon);var s=this.flowParseType();return this.state.inType=e,s},o.flowParseDeclareClass=function(t){return this.next(),this.flowParseInterfaceish(t,!0),this.finishNode(t,"DeclareClass")},o.flowParseDeclareFunction=function(t){this.next();var e=t.id=this.parseIdentifier(),s=this.startNode(),i=this.startNode();this.isRelational("<")?s.typeParameters=this.flowParseTypeParameterDeclaration():s.typeParameters=null,this.expect(r.types.parenL);var n=this.flowParseFunctionTypeParams();return s.params=n.params,s.rest=n.rest,this.expect(r.types.parenR),s.returnType=this.flowParseTypeInitialiser(),i.typeAnnotation=this.finishNode(s,"FunctionTypeAnnotation"),e.typeAnnotation=this.finishNode(i,"TypeAnnotation"),this.finishNode(e,e.type),this.semicolon(),this.finishNode(t,"DeclareFunction")},o.flowParseDeclare=function(t){return this.match(r.types._class)?this.flowParseDeclareClass(t):this.match(r.types._function)?this.flowParseDeclareFunction(t):this.match(r.types._var)?this.flowParseDeclareVariable(t):this.isContextual("module")?this.flowParseDeclareModule(t):this.isContextual("type")?this.flowParseDeclareTypeAlias(t):this.isContextual("interface")?this.flowParseDeclareInterface(t):void this.unexpected()},o.flowParseDeclareVariable=function(t){return this.next(),t.id=this.flowParseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(t,"DeclareVariable")},o.flowParseDeclareModule=function(t){this.next(),this.match(r.types.string)?t.id=this.parseExprAtom():t.id=this.parseIdentifier();var e=t.body=this.startNode(),s=e.body=[];for(this.expect(r.types.braceL);!this.match(r.types.braceR);){var i=this.startNode();this.next(),s.push(this.flowParseDeclare(i))}return this.expect(r.types.braceR),this.finishNode(e,"BlockStatement"),this.finishNode(t,"DeclareModule")},o.flowParseDeclareTypeAlias=function(t){return this.next(),this.flowParseTypeAlias(t),this.finishNode(t,"DeclareTypeAlias")},o.flowParseDeclareInterface=function(t){return this.next(),this.flowParseInterfaceish(t),this.finishNode(t,"DeclareInterface")},o.flowParseInterfaceish=function(t,e){if(t.id=this.parseIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t["extends"]=[],t.mixins=[],this.eat(r.types._extends))do t["extends"].push(this.flowParseInterfaceExtends());while(this.eat(r.types.comma));if(this.isContextual("mixins")){this.next();do t.mixins.push(this.flowParseInterfaceExtends());while(this.eat(r.types.comma))}t.body=this.flowParseObjectType(e)},o.flowParseInterfaceExtends=function(){var t=this.startNode();return t.id=this.parseIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterInstantiation():t.typeParameters=null,this.finishNode(t,"InterfaceExtends")},o.flowParseInterface=function(t){return this.flowParseInterfaceish(t,!1),this.finishNode(t,"InterfaceDeclaration")},o.flowParseTypeAlias=function(t){return t.id=this.parseIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.right=this.flowParseTypeInitialiser(r.types.eq),this.semicolon(),this.finishNode(t,"TypeAlias")},o.flowParseTypeParameterDeclaration=function(){var t=this.startNode();for(t.params=[],this.expectRelational("<");!this.isRelational(">");)t.params.push(this.flowParseExistentialTypeParam()||this.flowParseTypeAnnotatableIdentifier()),this.isRelational(">")||this.expect(r.types.comma);return this.expectRelational(">"),this.finishNode(t,"TypeParameterDeclaration")},o.flowParseExistentialTypeParam=function(){if(this.match(r.types.star)){var t=this.startNode();return this.next(),this.finishNode(t,"ExistentialTypeParam")}},o.flowParseTypeParameterInstantiation=function(){var t=this.startNode(),e=this.state.inType;for(t.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)t.params.push(this.flowParseExistentialTypeParam()||this.flowParseType()),this.isRelational(">")||this.expect(r.types.comma);return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterInstantiation")},o.flowParseObjectPropertyKey=function(){return this.match(r.types.num)||this.match(r.types.string)?this.parseExprAtom():this.parseIdentifier(!0)},o.flowParseObjectTypeIndexer=function(t,e){return t["static"]=e,this.expect(r.types.bracketL),t.id=this.flowParseObjectPropertyKey(),t.key=this.flowParseTypeInitialiser(),this.expect(r.types.bracketR),t.value=this.flowParseTypeInitialiser(),this.flowObjectTypeSemicolon(),this.finishNode(t,"ObjectTypeIndexer")},o.flowParseObjectTypeMethodish=function(t){for(t.params=[],t.rest=null,t.typeParameters=null,this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(r.types.parenL);this.match(r.types.name);)t.params.push(this.flowParseFunctionTypeParam()),this.match(r.types.parenR)||this.expect(r.types.comma);return this.eat(r.types.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),this.expect(r.types.parenR),t.returnType=this.flowParseTypeInitialiser(),this.finishNode(t,"FunctionTypeAnnotation")},o.flowParseObjectTypeMethod=function(t,e,s,i){var r=this.startNodeAt(t,e);return r.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t,e)),r["static"]=s,r.key=i,r.optional=!1,this.flowObjectTypeSemicolon(),this.finishNode(r,"ObjectTypeProperty")},o.flowParseObjectTypeCallProperty=function(t,e){var s=this.startNode();return t["static"]=e,t.value=this.flowParseObjectTypeMethodish(s),this.flowObjectTypeSemicolon(),this.finishNode(t,"ObjectTypeCallProperty")},o.flowParseObjectType=function(t){var e=this.startNode(),s=void 0,i=void 0,n=void 0;for(e.callProperties=[],e.properties=[],e.indexers=[],this.expect(r.types.braceL);!this.match(r.types.braceR);){var a=!1,o=this.state.start,u=this.state.startLoc;s=this.startNode(),t&&this.isContextual("static")&&(this.next(),n=!0),this.match(r.types.bracketL)?e.indexers.push(this.flowParseObjectTypeIndexer(s,n)):this.match(r.types.parenL)||this.isRelational("<")?e.callProperties.push(this.flowParseObjectTypeCallProperty(s,t)):(i=n&&this.match(r.types.colon)?this.parseIdentifier():this.flowParseObjectPropertyKey(),this.isRelational("<")||this.match(r.types.parenL)?e.properties.push(this.flowParseObjectTypeMethod(o,u,n,i)):(this.eat(r.types.question)&&(a=!0),s.key=i,s.value=this.flowParseTypeInitialiser(),s.optional=a,s["static"]=n,this.flowObjectTypeSemicolon(),e.properties.push(this.finishNode(s,"ObjectTypeProperty"))))}return this.expect(r.types.braceR),this.finishNode(e,"ObjectTypeAnnotation")},o.flowObjectTypeSemicolon=function(){this.eat(r.types.semi)||this.eat(r.types.comma)||this.match(r.types.braceR)||this.unexpected()},o.flowParseGenericType=function(t,e,s){var i=this.startNodeAt(t,e);for(i.typeParameters=null,i.id=s;this.eat(r.types.dot);){var n=this.startNodeAt(t,e);n.qualification=i.id,n.id=this.parseIdentifier(),i.id=this.finishNode(n,"QualifiedTypeIdentifier")}return this.isRelational("<")&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")},o.flowParseTypeofType=function(){var t=this.startNode();return this.expect(r.types._typeof),t.argument=this.flowParsePrimaryType(),this.finishNode(t,"TypeofTypeAnnotation")},o.flowParseTupleType=function(){var t=this.startNode();for(t.types=[],this.expect(r.types.bracketL);this.state.pos<this.input.length&&!this.match(r.types.bracketR)&&(t.types.push(this.flowParseType()),!this.match(r.types.bracketR));)this.expect(r.types.comma);return this.expect(r.types.bracketR),this.finishNode(t,"TupleTypeAnnotation")},o.flowParseFunctionTypeParam=function(){var t=!1,e=this.startNode();return e.name=this.parseIdentifier(),this.eat(r.types.question)&&(t=!0),e.optional=t,e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeParam")},o.flowParseFunctionTypeParams=function(){for(var t={params:[],rest:null};this.match(r.types.name);)t.params.push(this.flowParseFunctionTypeParam()),this.match(r.types.parenR)||this.expect(r.types.comma);return this.eat(r.types.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),t},o.flowIdentToTypeAnnotation=function(t,e,s,i){switch(i.name){case"any":return this.finishNode(s,"AnyTypeAnnotation");case"void":return this.finishNode(s,"VoidTypeAnnotation");case"bool":case"boolean":return this.finishNode(s,"BooleanTypeAnnotation");case"mixed":return this.finishNode(s,"MixedTypeAnnotation");case"number":return this.finishNode(s,"NumberTypeAnnotation");case"string":return this.finishNode(s,"StringTypeAnnotation");default:return this.flowParseGenericType(t,e,i)}},o.flowParsePrimaryType=function(){var t=this.state.start,e=this.state.startLoc,s=this.startNode(),i=void 0,n=void 0,a=!1;switch(this.state.type){case r.types.name:return this.flowIdentToTypeAnnotation(t,e,s,this.parseIdentifier());case r.types.braceL:return this.flowParseObjectType();case r.types.bracketL:return this.flowParseTupleType();case r.types.relational:if("<"===this.state.value)return s.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(r.types.parenL),i=this.flowParseFunctionTypeParams(),s.params=i.params,s.rest=i.rest,this.expect(r.types.parenR),this.expect(r.types.arrow),s.returnType=this.flowParseType(),this.finishNode(s,"FunctionTypeAnnotation");case r.types.parenL:if(this.next(),!this.match(r.types.parenR)&&!this.match(r.types.ellipsis))if(this.match(r.types.name)){var o=this.lookahead().type;a=o!==r.types.question&&o!==r.types.colon}else a=!0;return a?(n=this.flowParseType(),this.expect(r.types.parenR),this.eat(r.types.arrow)&&this.raise(s,"Unexpected token =>. It looks like you are trying to write a function type, but you ended up writing a grouped type followed by an =>, which is a syntax error. Remember, function type parameters are named so function types look like (name1: type1, name2: type2) => returnType. You probably wrote (type1) => returnType"),n):(i=this.flowParseFunctionTypeParams(),s.params=i.params,s.rest=i.rest,this.expect(r.types.parenR),this.expect(r.types.arrow),s.returnType=this.flowParseType(),s.typeParameters=null,this.finishNode(s,"FunctionTypeAnnotation"));case r.types.string:return s.value=this.state.value,this.addExtra(s,"rawValue",s.value),this.addExtra(s,"raw",this.input.slice(this.state.start,this.state.end)),this.next(),this.finishNode(s,"StringLiteralTypeAnnotation");case r.types._true:case r.types._false:return s.value=this.match(r.types._true),this.next(),this.finishNode(s,"BooleanLiteralTypeAnnotation");case r.types.num:return s.value=this.state.value,this.addExtra(s,"rawValue",s.value),this.addExtra(s,"raw",this.input.slice(this.state.start,this.state.end)),this.next(),this.finishNode(s,"NumericLiteralTypeAnnotation");case r.types._null:return s.value=this.match(r.types._null),this.next(),this.finishNode(s,"NullLiteralTypeAnnotation");case r.types._this:return s.value=this.match(r.types._this),this.next(),this.finishNode(s,"ThisTypeAnnotation");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType()}this.unexpected()},o.flowParsePostfixType=function(){var t=this.startNode(),e=t.elementType=this.flowParsePrimaryType();return this.match(r.types.bracketL)?(this.expect(r.types.bracketL),this.expect(r.types.bracketR),this.finishNode(t,"ArrayTypeAnnotation")):e},o.flowParsePrefixType=function(){var t=this.startNode();return this.eat(r.types.question)?(t.typeAnnotation=this.flowParsePrefixType(),this.finishNode(t,"NullableTypeAnnotation")):this.flowParsePostfixType()},o.flowParseIntersectionType=function(){var t=this.startNode(),e=this.flowParsePrefixType();for(t.types=[e];this.eat(r.types.bitwiseAND);)t.types.push(this.flowParsePrefixType());return 1===t.types.length?e:this.finishNode(t,"IntersectionTypeAnnotation")},o.flowParseUnionType=function(){var t=this.startNode(),e=this.flowParseIntersectionType();for(t.types=[e];this.eat(r.types.bitwiseOR);)t.types.push(this.flowParseIntersectionType());return 1===t.types.length?e:this.finishNode(t,"UnionTypeAnnotation")},o.flowParseType=function(){var t=this.state.inType;this.state.inType=!0;var e=this.flowParseUnionType();return this.state.inType=t,e},o.flowParseTypeAnnotation=function(){var t=this.startNode();return t.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(t,"TypeAnnotation")},o.flowParseTypeAnnotatableIdentifier=function(t,e){var s=this.parseIdentifier(),i=!1;return e&&this.eat(r.types.question)&&(this.expect(r.types.question),i=!0),(t||this.match(r.types.colon))&&(s.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(s,s.type)),i&&(s.optional=!0,this.finishNode(s,s.type)),s},s["default"]=function(t){function e(t){return t.expression.typeAnnotation=t.typeAnnotation,t.expression}t.extend("parseFunctionBody",function(t){return function(e,s){return this.match(r.types.colon)&&!s&&(e.returnType=this.flowParseTypeAnnotation()),t.call(this,e,s)}}),t.extend("parseStatement",function(t){return function(e,s){if(this.state.strict&&this.match(r.types.name)&&"interface"===this.state.value){var i=this.startNode();return this.next(),this.flowParseInterface(i)}return t.call(this,e,s)}}),t.extend("parseExpressionStatement",function(t){return function(e,s){if("Identifier"===s.type)if("declare"===s.name){if(this.match(r.types._class)||this.match(r.types.name)||this.match(r.types._function)||this.match(r.types._var))return this.flowParseDeclare(e)}else if(this.match(r.types.name)){if("interface"===s.name)return this.flowParseInterface(e);if("type"===s.name)return this.flowParseTypeAlias(e)}return t.call(this,e,s)}}),t.extend("shouldParseExportDeclaration",function(t){return function(){return this.isContextual("type")||this.isContextual("interface")||t.call(this)}}),t.extend("parseParenItem",function(){return function(t,e,s,i){var n=this.state.potentialArrowAt=s;if(this.match(r.types.colon)){var a=this.startNodeAt(e,s);if(a.expression=t,a.typeAnnotation=this.flowParseTypeAnnotation(),i&&!this.match(r.types.arrow)&&this.unexpected(),n&&this.eat(r.types.arrow)){var o="SequenceExpression"===t.type?t.expressions:[t],u=this.parseArrowExpression(this.startNodeAt(e,s),o);return u.returnType=a.typeAnnotation,u}return this.finishNode(a,"TypeCastExpression")}return t}}),t.extend("parseExport",function(t){return function(e){return e=t.call(this,e),"ExportNamedDeclaration"===e.type&&(e.exportKind=e.exportKind||"value"),e}}),t.extend("parseExportDeclaration",function(t){return function(e){if(this.isContextual("type")){e.exportKind="type";var s=this.startNode();return this.next(),this.match(r.types.braceL)?(e.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(e),null):this.flowParseTypeAlias(s)}if(this.isContextual("interface")){e.exportKind="type";var s=this.startNode();return this.next(),this.flowParseInterface(s)}return t.call(this,e)}}),t.extend("parseClassId",function(t){return function(e){t.apply(this,arguments),this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}}),t.extend("isKeyword",function(t){return function(e){return this.state.inType&&"void"===e?!1:t.call(this,e)}}),t.extend("readToken",function(t){return function(e){return!this.state.inType||62!==e&&60!==e?t.call(this,e):this.finishOp(r.types.relational,1)}}),t.extend("jsx_readToken",function(t){return function(){return this.state.inType?void 0:t.call(this)}}),t.extend("toAssignable",function(t){return function(s){return"TypeCastExpression"===s.type?e(s):t.apply(this,arguments)}}),t.extend("toAssignableList",function(t){return function(s,i){for(var r=0;r<s.length;r++){var n=s[r];n&&"TypeCastExpression"===n.type&&(s[r]=e(n))}return t.call(this,s,i)}}),t.extend("toReferencedList",function(){return function(t){for(var e=0;e<t.length;e++){var s=t[e];s&&s._exprListItem&&"TypeCastExpression"===s.type&&this.raise(s.start,"Unexpected type cast")}return t}}),t.extend("parseExprListItem",function(t){return function(e,s){var i=this.startNode(),n=t.call(this,e,s);return this.match(r.types.colon)?(i._exprListItem=!0,i.expression=n,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")):n}}),t.extend("checkLVal",function(t){return function(e){return"TypeCastExpression"!==e.type?t.apply(this,arguments):void 0}}),t.extend("parseClassProperty",function(t){return function(e){return this.match(r.types.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),t.call(this,e)}}),t.extend("isClassProperty",function(t){return function(){return this.match(r.types.colon)||t.call(this)}}),t.extend("parseClassMethod",function(){return function(t,e,s,i){this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.parseMethod(e,s,i),t.body.push(this.finishNode(e,"ClassMethod"))}}),t.extend("parseClassSuper",function(t){return function(e,s){if(t.call(this,e,s),e.superClass&&this.isRelational("<")&&(e.superTypeParameters=this.flowParseTypeParameterInstantiation()),this.isContextual("implements")){this.next();var i=e["implements"]=[];do{var n=this.startNode();n.id=this.parseIdentifier(),this.isRelational("<")?n.typeParameters=this.flowParseTypeParameterInstantiation():n.typeParameters=null,i.push(this.finishNode(n,"ClassImplements"))}while(this.eat(r.types.comma))}}}),t.extend("parseObjPropValue",function(t){return function(e){var s=void 0;this.isRelational("<")&&(s=this.flowParseTypeParameterDeclaration(),this.match(r.types.parenL)||this.unexpected()),t.apply(this,arguments),s&&((e.value||e).typeParameters=s)}}),t.extend("parseAssignableListItemTypes",function(){return function(t){return this.eat(r.types.question)&&(t.optional=!0),this.match(r.types.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),this.finishNode(t,t.type),t}}),t.extend("parseImportSpecifiers",function(t){return function(e){e.importKind="value";var s=null;if(this.match(r.types._typeof)?s="typeof":this.isContextual("type")&&(s="type"),s){var i=this.lookahead();(i.type===r.types.name&&"from"!==i.value||i.type===r.types.braceL||i.type===r.types.star)&&(this.next(),e.importKind=s)}t.call(this,e)}}),t.extend("parseFunctionParams",function(t){return function(e){this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),t.call(this,e)}}),t.extend("parseVarHead",function(t){return function(e){t.call(this,e),this.match(r.types.colon)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e.id,e.id.type))}}),t.extend("parseAsyncArrowFromCallExpression",function(t){return function(e,s){return this.match(r.types.colon)&&(e.returnType=this.flowParseTypeAnnotation()),t.call(this,e,s)}}),t.extend("shouldParseAsyncArrow",function(t){return function(){return this.match(r.types.colon)||t.call(this)}}),t.extend("parseParenAndDistinguishExpression",function(t){return function(e,s,i,n){if(e=e||this.state.start,s=s||this.state.startLoc,i&&this.lookahead().type===r.types.parenR){this.expect(r.types.parenL),this.expect(r.types.parenR);var a=this.startNodeAt(e,s);return this.match(r.types.colon)&&(a.returnType=this.flowParseTypeAnnotation()),this.expect(r.types.arrow),this.parseArrowExpression(a,[],n)}var a=t.call(this,e,s,i,n);if(!this.match(r.types.colon))return a;var o=this.state.clone();try{return this.parseParenItem(a,e,s,!0)}catch(u){if(u instanceof SyntaxError)return this.state=o,a;throw u}}})},e.exports=s["default"]},{"../parser":5,"../tokenizer/types":17,"babel-runtime/helpers/interop-require-default":26}],12:[function(t,e,s){"use strict";function i(t){return"JSXIdentifier"===t.type?t.name:"JSXNamespacedName"===t.type?t.namespace.name+":"+t.name.name:"JSXMemberExpression"===t.type?i(t.object)+"."+i(t.property):void 0}var r=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var n=t("./xhtml"),a=r(n),o=t("../../tokenizer/types"),u=t("../../tokenizer/context"),p=t("../../parser"),c=r(p),l=t("../../util/identifier"),h=t("../../util/whitespace"),f=/^[\da-fA-F]+$/,d=/^\d+$/;u.types.j_oTag=new u.TokContext("<tag",!1),u.types.j_cTag=new u.TokContext("</tag",!1),u.types.j_expr=new u.TokContext("<tag>...</tag>",!0,!0),o.types.jsxName=new o.TokenType("jsxName"),o.types.jsxText=new o.TokenType("jsxText",{beforeExpr:!0}),o.types.jsxTagStart=new o.TokenType("jsxTagStart"),o.types.jsxTagEnd=new o.TokenType("jsxTagEnd"),o.types.jsxTagStart.updateContext=function(){this.state.context.push(u.types.j_expr),this.state.context.push(u.types.j_oTag),this.state.exprAllowed=!1},o.types.jsxTagEnd.updateContext=function(t){var e=this.state.context.pop();e===u.types.j_oTag&&t===o.types.slash||e===u.types.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===u.types.j_expr):this.state.exprAllowed=!0};var y=c["default"].prototype;y.jsxReadToken=function(){for(var t="",e=this.state.pos;;){ this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated JSX contents");var s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:return this.state.pos===this.state.start?60===s&&this.state.exprAllowed?(++this.state.pos,this.finishToken(o.types.jsxTagStart)):this.getTokenFromCode(s):(t+=this.input.slice(e,this.state.pos),this.finishToken(o.types.jsxText,t));case 38:t+=this.input.slice(e,this.state.pos),t+=this.jsxReadEntity(),e=this.state.pos;break;default:h.isNewLine(s)?(t+=this.input.slice(e,this.state.pos),t+=this.jsxReadNewLine(!0),e=this.state.pos):++this.state.pos}}},y.jsxReadNewLine=function(t){var e=this.input.charCodeAt(this.state.pos),s=void 0;return++this.state.pos,13===e&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,s=t?"\n":"\r\n"):s=String.fromCharCode(e),++this.state.curLine,this.state.lineStart=this.state.pos,s},y.jsxReadString=function(t){for(var e="",s=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var i=this.input.charCodeAt(this.state.pos);if(i===t)break;38===i?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadEntity(),s=this.state.pos):h.isNewLine(i)?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}return e+=this.input.slice(s,this.state.pos++),this.finishToken(o.types.string,e)},y.jsxReadEntity=function(){for(var t="",e=0,s=void 0,i=this.input[this.state.pos],r=++this.state.pos;this.state.pos<this.input.length&&e++<10;){if(i=this.input[this.state.pos++],";"===i){"#"===t[0]?"x"===t[1]?(t=t.substr(2),f.test(t)&&(s=String.fromCharCode(parseInt(t,16)))):(t=t.substr(1),d.test(t)&&(s=String.fromCharCode(parseInt(t,10)))):s=a["default"][t];break}t+=i}return s?s:(this.state.pos=r,"&")},y.jsxReadWord=function(){var t=void 0,e=this.state.pos;do t=this.input.charCodeAt(++this.state.pos);while(l.isIdentifierChar(t)||45===t);return this.finishToken(o.types.jsxName,this.input.slice(e,this.state.pos))},y.jsxParseIdentifier=function(){var t=this.startNode();return this.match(o.types.jsxName)?t.name=this.state.value:this.state.type.keyword?t.name=this.state.type.keyword:this.unexpected(),this.next(),this.finishNode(t,"JSXIdentifier")},y.jsxParseNamespacedName=function(){var t=this.state.start,e=this.state.startLoc,s=this.jsxParseIdentifier();if(!this.eat(o.types.colon))return s;var i=this.startNodeAt(t,e);return i.namespace=s,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")},y.jsxParseElementName=function(){for(var t=this.state.start,e=this.state.startLoc,s=this.jsxParseNamespacedName();this.eat(o.types.dot);){var i=this.startNodeAt(t,e);i.object=s,i.property=this.jsxParseIdentifier(),s=this.finishNode(i,"JSXMemberExpression")}return s},y.jsxParseAttributeValue=function(){var t=void 0;switch(this.state.type){case o.types.braceL:if(t=this.jsxParseExpressionContainer(),"JSXEmptyExpression"!==t.expression.type)return t;this.raise(t.start,"JSX attributes must only be assigned a non-empty expression");case o.types.jsxTagStart:case o.types.string:return t=this.parseExprAtom(),t.extra=null,t;default:this.raise(this.state.start,"JSX value should be either an expression or a quoted JSX text")}},y.jsxParseEmptyExpression=function(){var t=this.startNodeAt(this.lastTokEnd,this.lastTokEndLoc);return this.finishNodeAt(t,"JSXEmptyExpression",this.start,this.startLoc)},y.jsxParseExpressionContainer=function(){var t=this.startNode();return this.next(),this.match(o.types.braceR)?t.expression=this.jsxParseEmptyExpression():t.expression=this.parseExpression(),this.expect(o.types.braceR),this.finishNode(t,"JSXExpressionContainer")},y.jsxParseAttribute=function(){var t=this.startNode();return this.eat(o.types.braceL)?(this.expect(o.types.ellipsis),t.argument=this.parseMaybeAssign(),this.expect(o.types.braceR),this.finishNode(t,"JSXSpreadAttribute")):(t.name=this.jsxParseNamespacedName(),t.value=this.eat(o.types.eq)?this.jsxParseAttributeValue():null,this.finishNode(t,"JSXAttribute"))},y.jsxParseOpeningElementAt=function(t,e){var s=this.startNodeAt(t,e);for(s.attributes=[],s.name=this.jsxParseElementName();!this.match(o.types.slash)&&!this.match(o.types.jsxTagEnd);)s.attributes.push(this.jsxParseAttribute());return s.selfClosing=this.eat(o.types.slash),this.expect(o.types.jsxTagEnd),this.finishNode(s,"JSXOpeningElement")},y.jsxParseClosingElementAt=function(t,e){var s=this.startNodeAt(t,e);return s.name=this.jsxParseElementName(),this.expect(o.types.jsxTagEnd),this.finishNode(s,"JSXClosingElement")},y.jsxParseElementAt=function(t,e){var s=this.startNodeAt(t,e),r=[],n=this.jsxParseOpeningElementAt(t,e),a=null;if(!n.selfClosing){t:for(;;)switch(this.state.type){case o.types.jsxTagStart:if(t=this.state.start,e=this.state.startLoc,this.next(),this.eat(o.types.slash)){a=this.jsxParseClosingElementAt(t,e);break t}r.push(this.jsxParseElementAt(t,e));break;case o.types.jsxText:r.push(this.parseExprAtom());break;case o.types.braceL:r.push(this.jsxParseExpressionContainer());break;default:this.unexpected()}i(a.name)!==i(n.name)&&this.raise(a.start,"Expected corresponding JSX closing tag for <"+i(n.name)+">")}return s.openingElement=n,s.closingElement=a,s.children=r,this.match(o.types.relational)&&"<"===this.state.value&&this.raise(this.state.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(s,"JSXElement")},y.jsxParseElement=function(){var t=this.state.start,e=this.state.startLoc;return this.next(),this.jsxParseElementAt(t,e)},s["default"]=function(t){t.extend("parseExprAtom",function(t){return function(e){if(this.match(o.types.jsxText)){var s=this.parseLiteral(this.state.value,"JSXText");return s.extra=null,s}return this.match(o.types.jsxTagStart)?this.jsxParseElement():t.call(this,e)}}),t.extend("readToken",function(t){return function(e){var s=this.curContext();if(s===u.types.j_expr)return this.jsxReadToken();if(s===u.types.j_oTag||s===u.types.j_cTag){if(l.isIdentifierStart(e))return this.jsxReadWord();if(62===e)return++this.state.pos,this.finishToken(o.types.jsxTagEnd);if((34===e||39===e)&&s===u.types.j_oTag)return this.jsxReadString(e)}return 60===e&&this.state.exprAllowed?(++this.state.pos,this.finishToken(o.types.jsxTagStart)):t.call(this,e)}}),t.extend("updateContext",function(t){return function(e){if(this.match(o.types.braceL)){var s=this.curContext();s===u.types.j_oTag?this.state.context.push(u.types.b_expr):s===u.types.j_expr?this.state.context.push(u.types.b_tmpl):t.call(this,e),this.state.exprAllowed=!0}else{if(!this.match(o.types.slash)||e!==o.types.jsxTagStart)return t.call(this,e);this.state.context.length-=2,this.state.context.push(u.types.j_cTag),this.state.exprAllowed=!1}}})},e.exports=s["default"]},{"../../parser":5,"../../tokenizer/context":14,"../../tokenizer/types":17,"../../util/identifier":18,"../../util/whitespace":20,"./xhtml":13,"babel-runtime/helpers/interop-require-default":26}],13:[function(t,e,s){"use strict";s.__esModule=!0,s["default"]={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},e.exports=s["default"]},{}],14:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0;var r=t("./types"),n=t("../util/whitespace"),a=function u(t,e,s,r){i(this,u),this.token=t,this.isExpr=!!e,this.preserveSpace=!!s,this.override=r};s.TokContext=a;var o={b_stat:new a("{",!1),b_expr:new a("{",!0),b_tmpl:new a("${",!0),p_stat:new a("(",!1),p_expr:new a("(",!0),q_tmpl:new a("`",!0,!0,function(t){return t.readTmplToken()}),f_expr:new a("function",!0)};s.types=o,r.types.parenR.updateContext=r.types.braceR.updateContext=function(){if(1===this.state.context.length)return void(this.state.exprAllowed=!0);var t=this.state.context.pop();t===o.b_stat&&this.curContext()===o.f_expr?(this.state.context.pop(),this.state.exprAllowed=!1):t===o.b_tmpl?this.state.exprAllowed=!0:this.state.exprAllowed=!t.isExpr},r.types.name.updateContext=function(t){this.state.exprAllowed=!1,(t===r.types._let||t===r.types._const||t===r.types._var)&&n.lineBreak.test(this.input.slice(this.state.end))&&(this.state.exprAllowed=!0)},r.types.braceL.updateContext=function(t){this.state.context.push(this.braceIsBlock(t)?o.b_stat:o.b_expr),this.state.exprAllowed=!0},r.types.dollarBraceL.updateContext=function(){this.state.context.push(o.b_tmpl),this.state.exprAllowed=!0},r.types.parenL.updateContext=function(t){var e=t===r.types._if||t===r.types._for||t===r.types._with||t===r.types._while;this.state.context.push(e?o.p_stat:o.p_expr),this.state.exprAllowed=!0},r.types.incDec.updateContext=function(){},r.types._function.updateContext=function(){this.curContext()!==o.b_stat&&this.state.context.push(o.f_expr),this.state.exprAllowed=!1},r.types.backQuote.updateContext=function(){this.curContext()===o.q_tmpl?this.state.context.pop():this.state.context.push(o.q_tmpl),this.state.exprAllowed=!1}},{"../util/whitespace":20,"./types":17,"babel-runtime/helpers/class-call-check":24}],15:[function(t,e,s){"use strict";function i(t){return 65535>=t?String.fromCharCode(t):String.fromCharCode((t-65536>>10)+55296,(t-65536&1023)+56320)}var r=t("babel-runtime/helpers/class-call-check")["default"],n=t("babel-runtime/helpers/interop-require-default")["default"];s.__esModule=!0;var a=t("../util/identifier"),o=t("./types"),u=t("./context"),p=t("../util/location"),c=t("../util/whitespace"),l=t("./state"),h=n(l),f=function y(t){r(this,y),this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new p.SourceLocation(t.startLoc,t.endLoc)};s.Token=f;var d=function(){function t(e,s){r(this,t),this.state=new h["default"],this.state.init(e,s)}return t.prototype.next=function(){this.isLookahead||this.state.tokens.push(new f(this.state)),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},t.prototype.eat=function(t){return this.match(t)?(this.next(),!0):!1},t.prototype.match=function(t){return this.state.type===t},t.prototype.isKeyword=function(t){return a.isKeyword(t)},t.prototype.lookahead=function(){var t=this.state;this.state=t.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;var e=this.state.clone(!0);return this.state=t,e},t.prototype.setStrict=function(t){if(this.state.strict=t,this.match(o.types.num)||this.match(o.types.string)){for(this.state.pos=this.state.start;this.state.pos<this.state.lineStart;)this.state.lineStart=this.input.lastIndexOf("\n",this.state.lineStart-2)+1,--this.state.curLine;this.nextToken()}},t.prototype.curContext=function(){return this.state.context[this.state.context.length-1]},t.prototype.nextToken=function(){var t=this.curContext();return t&&t.preserveSpace||this.skipSpace(),this.state.containsOctal=!1,this.state.octalPosition=null,this.state.start=this.state.pos,this.state.startLoc=this.state.curPosition(),this.state.pos>=this.input.length?this.finishToken(o.types.eof):t.override?t.override(this):this.readToken(this.fullCharCodeAtPos())},t.prototype.readToken=function(t){return a.isIdentifierStart(t)||92===t?this.readWord():this.getTokenFromCode(t)},t.prototype.fullCharCodeAtPos=function(){var t=this.input.charCodeAt(this.state.pos);if(55295>=t||t>=57344)return t;var e=this.input.charCodeAt(this.state.pos+1);return(t<<10)+e-56613888},t.prototype.pushComment=function(t,e,s,i,r,n){var a={type:t?"CommentBlock":"CommentLine",value:e,start:s,end:i,loc:new p.SourceLocation(r,n)};this.isLookahead||(this.state.tokens.push(a),this.state.comments.push(a)),this.addComment(a)},t.prototype.skipBlockComment=function(){var t=this.state.curPosition(),e=this.state.pos,s=this.input.indexOf("*/",this.state.pos+=2);-1===s&&this.raise(this.state.pos-2,"Unterminated comment"),this.state.pos=s+2,c.lineBreakG.lastIndex=e;for(var i=void 0;(i=c.lineBreakG.exec(this.input))&&i.index<this.state.pos;)++this.state.curLine,this.state.lineStart=i.index+i[0].length;this.pushComment(!0,this.input.slice(e+2,s),e,this.state.pos,t,this.state.curPosition())},t.prototype.skipLineComment=function(t){for(var e=this.state.pos,s=this.state.curPosition(),i=this.input.charCodeAt(this.state.pos+=t);this.state.pos<this.input.length&&10!==i&&13!==i&&8232!==i&&8233!==i;)++this.state.pos,i=this.input.charCodeAt(this.state.pos);this.pushComment(!1,this.input.slice(e+t,this.state.pos),e,this.state.pos,s,this.state.curPosition())},t.prototype.skipSpace=function(){t:for(;this.state.pos<this.input.length;){var t=this.input.charCodeAt(this.state.pos);switch(t){case 32:case 160:++this.state.pos;break;case 13:10===this.input.charCodeAt(this.state.pos+1)&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break t}break;default:if(!(t>8&&14>t||t>=5760&&c.nonASCIIwhitespace.test(String.fromCharCode(t))))break t;++this.state.pos}}},t.prototype.finishToken=function(t,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var s=this.state.type;this.state.type=t,this.state.value=e,this.updateContext(s)},t.prototype.readToken_dot=function(){var t=this.input.charCodeAt(this.state.pos+1);if(t>=48&&57>=t)return this.readNumber(!0);var e=this.input.charCodeAt(this.state.pos+2);return 46===t&&46===e?(this.state.pos+=3,this.finishToken(o.types.ellipsis)):(++this.state.pos,this.finishToken(o.types.dot))},t.prototype.readToken_slash=function(){if(this.state.exprAllowed)return++this.state.pos,this.readRegexp();var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(o.types.assign,2):this.finishOp(o.types.slash,1)},t.prototype.readToken_mult_modulo=function(t){var e=42===t?o.types.star:o.types.modulo,s=1,i=this.input.charCodeAt(this.state.pos+1);return 42===i&&this.hasPlugin("exponentiationOperator")&&(s++,i=this.input.charCodeAt(this.state.pos+2),e=o.types.exponent),61===i&&(s++,e=o.types.assign),this.finishOp(e,s)},t.prototype.readToken_pipe_amp=function(t){var e=this.input.charCodeAt(this.state.pos+1);return e===t?this.finishOp(124===t?o.types.logicalOR:o.types.logicalAND,2):61===e?this.finishOp(o.types.assign,2):this.finishOp(124===t?o.types.bitwiseOR:o.types.bitwiseAND,1)},t.prototype.readToken_caret=function(){var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(o.types.assign,2):this.finishOp(o.types.bitwiseXOR,1)},t.prototype.readToken_plus_min=function(t){var e=this.input.charCodeAt(this.state.pos+1);return e===t?45===e&&62===this.input.charCodeAt(this.state.pos+2)&&c.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(o.types.incDec,2):61===e?this.finishOp(o.types.assign,2):this.finishOp(o.types.plusMin,1)},t.prototype.readToken_lt_gt=function(t){var e=this.input.charCodeAt(this.state.pos+1),s=1;return e===t?(s=62===t&&62===this.input.charCodeAt(this.state.pos+2)?3:2,61===this.input.charCodeAt(this.state.pos+s)?this.finishOp(o.types.assign,s+1):this.finishOp(o.types.bitShift,s)):33===e&&60===t&&45===this.input.charCodeAt(this.state.pos+2)&&45===this.input.charCodeAt(this.state.pos+3)?(this.inModule&&this.unexpected(),this.skipLineComment(4),this.skipSpace(),this.nextToken()):(61===e&&(s=61===this.input.charCodeAt(this.state.pos+2)?3:2),this.finishOp(o.types.relational,s))},t.prototype.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.state.pos+1);return 61===e?this.finishOp(o.types.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2):61===t&&62===e?(this.state.pos+=2,this.finishToken(o.types.arrow)):this.finishOp(61===t?o.types.eq:o.types.prefix,1)},t.prototype.getTokenFromCode=function(t){switch(t){case 46:return this.readToken_dot();case 40:return++this.state.pos,this.finishToken(o.types.parenL);case 41:return++this.state.pos,this.finishToken(o.types.parenR);case 59:return++this.state.pos,this.finishToken(o.types.semi);case 44:return++this.state.pos,this.finishToken(o.types.comma);case 91:return++this.state.pos,this.finishToken(o.types.bracketL);case 93:return++this.state.pos,this.finishToken(o.types.bracketR);case 123:return++this.state.pos,this.finishToken(o.types.braceL);case 125:return++this.state.pos,this.finishToken(o.types.braceR);case 58:return this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(o.types.doubleColon,2):(++this.state.pos,this.finishToken(o.types.colon));case 63:return++this.state.pos,this.finishToken(o.types.question);case 64:return++this.state.pos,this.finishToken(o.types.at);case 96:return++this.state.pos,this.finishToken(o.types.backQuote);case 48:var e=this.input.charCodeAt(this.state.pos+1);if(120===e||88===e)return this.readRadixNumber(16);if(111===e||79===e)return this.readRadixNumber(8);if(98===e||66===e)return this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(t);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo(t);case 124:case 38:return this.readToken_pipe_amp(t);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(t);case 60:case 62:return this.readToken_lt_gt(t);case 61:case 33:return this.readToken_eq_excl(t);case 126:return this.finishOp(o.types.prefix,1)}this.raise(this.state.pos,"Unexpected character '"+i(t)+"'")},t.prototype.finishOp=function(t,e){var s=this.input.slice(this.state.pos,this.state.pos+e);return this.state.pos+=e,this.finishToken(t,s)},t.prototype.readRegexp=function(){for(var t=void 0,e=void 0,s=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var i=this.input.charAt(this.state.pos);if(c.lineBreak.test(i)&&this.raise(s,"Unterminated regular expression"),t)t=!1;else{if("["===i)e=!0;else if("]"===i&&e)e=!1;else if("/"===i&&!e)break;t="\\"===i}++this.state.pos}var r=this.input.slice(s,this.state.pos);++this.state.pos;var n=this.readWord1();if(n){var a=/^[gmsiyu]*$/;a.test(n)||this.raise(s,"Invalid regular expression flag")}return this.finishToken(o.types.regexp,{pattern:r,flags:n})},t.prototype.readInt=function(t,e){for(var s=this.state.pos,i=0,r=0,n=null==e?1/0:e;n>r;++r){var a=this.input.charCodeAt(this.state.pos),o=void 0;if(o=a>=97?a-97+10:a>=65?a-65+10:a>=48&&57>=a?a-48:1/0,o>=t)break;++this.state.pos,i=i*t+o}return this.state.pos===s||null!=e&&this.state.pos-s!==e?null:i},t.prototype.readRadixNumber=function(t){this.state.pos+=2;var e=this.readInt(t);return null==e&&this.raise(this.state.start+2,"Expected number in radix "+t),a.isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number"),this.finishToken(o.types.num,e)},t.prototype.readNumber=function(t){var e=this.state.pos,s=!1,i=48===this.input.charCodeAt(this.state.pos);t||null!==this.readInt(10)||this.raise(e,"Invalid number");var r=this.input.charCodeAt(this.state.pos);46===r&&(++this.state.pos,this.readInt(10),s=!0,r=this.input.charCodeAt(this.state.pos)),(69===r||101===r)&&(r=this.input.charCodeAt(++this.state.pos),(43===r||45===r)&&++this.state.pos,null===this.readInt(10)&&this.raise(e,"Invalid number"),s=!0),a.isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number");var n=this.input.slice(e,this.state.pos),u=void 0;return s?u=parseFloat(n):i&&1!==n.length?/[89]/.test(n)||this.state.strict?this.raise(e,"Invalid number"):u=parseInt(n,8):u=parseInt(n,10),this.finishToken(o.types.num,u)},t.prototype.readCodePoint=function(){var t=this.input.charCodeAt(this.state.pos),e=void 0;if(123===t){var s=++this.state.pos;e=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos),++this.state.pos,e>1114111&&this.raise(s,"Code point out of bounds")}else e=this.readHexChar(4);return e},t.prototype.readString=function(t){for(var e="",s=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var i=this.input.charCodeAt(this.state.pos);if(i===t)break;92===i?(e+=this.input.slice(s,this.state.pos),e+=this.readEscapedChar(!1),s=this.state.pos):(c.isNewLine(i)&&this.raise(this.state.start,"Unterminated string constant"),++this.state.pos)}return e+=this.input.slice(s,this.state.pos++),this.finishToken(o.types.string,e)},t.prototype.readTmplToken=function(){for(var t="",e=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated template");var s=this.input.charCodeAt(this.state.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(o.types.template)?36===s?(this.state.pos+=2,this.finishToken(o.types.dollarBraceL)):(++this.state.pos,this.finishToken(o.types.backQuote)):(t+=this.input.slice(e,this.state.pos),this.finishToken(o.types.template,t));if(92===s)t+=this.input.slice(e,this.state.pos),t+=this.readEscapedChar(!0),e=this.state.pos;else if(c.isNewLine(s)){switch(t+=this.input.slice(e,this.state.pos),++this.state.pos,s){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:t+="\n";break;default:t+=String.fromCharCode(s)}++this.state.curLine,this.state.lineStart=this.state.pos,e=this.state.pos}else++this.state.pos}},t.prototype.readEscapedChar=function(t){var e=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,e){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return i(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\x0B";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:return this.state.lineStart=this.state.pos,++this.state.curLine,"";default:if(e>=48&&55>=e){var s=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],r=parseInt(s,8);return r>255&&(s=s.slice(0,-1),r=parseInt(s,8)),r>0&&(this.state.containsOctal||(this.state.containsOctal=!0,this.state.octalPosition=this.state.pos-2),(this.state.strict||t)&&this.raise(this.state.pos-2,"Octal literal in strict mode")),this.state.pos+=s.length-1,String.fromCharCode(r)}return String.fromCharCode(e)}},t.prototype.readHexChar=function(t){var e=this.state.pos,s=this.readInt(16,t);return null===s&&this.raise(e,"Bad character escape sequence"),s},t.prototype.readWord1=function(){this.state.containsEsc=!1;for(var t="",e=!0,s=this.state.pos;this.state.pos<this.input.length;){var r=this.fullCharCodeAtPos();if(a.isIdentifierChar(r))this.state.pos+=65535>=r?1:2;else{if(92!==r)break;this.state.containsEsc=!0,t+=this.input.slice(s,this.state.pos);var n=this.state.pos;117!==this.input.charCodeAt(++this.state.pos)&&this.raise(this.state.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.state.pos;var o=this.readCodePoint();(e?a.isIdentifierStart:a.isIdentifierChar)(o,!0)||this.raise(n,"Invalid Unicode escape"),t+=i(o),s=this.state.pos}e=!1}return t+this.input.slice(s,this.state.pos)},t.prototype.readWord=function(){var t=this.readWord1(),e=o.types.name;return!this.state.containsEsc&&this.isKeyword(t)&&(e=o.keywords[t]),this.finishToken(e,t)},t.prototype.braceIsBlock=function(t){if(t===o.types.colon){var e=this.curContext();if(e===u.types.b_stat||e===u.types.b_expr)return!e.isExpr}return t===o.types._return?c.lineBreak.test(this.input.slice(this.state.lastTokEnd,this.state.start)):t===o.types._else||t===o.types.semi||t===o.types.eof||t===o.types.parenR?!0:t===o.types.braceL?this.curContext()===u.types.b_stat:!this.state.exprAllowed},t.prototype.updateContext=function(t){var e=void 0,s=this.state.type;s.keyword&&t===o.types.dot?this.state.exprAllowed=!1:(e=s.updateContext)?e.call(this,t):this.state.exprAllowed=s.beforeExpr},t}();s["default"]=d},{"../util/identifier":18,"../util/location":19,"../util/whitespace":20,"./context":14,"./state":16,"./types":17,"babel-runtime/helpers/class-call-check":24,"babel-runtime/helpers/interop-require-default":26}],16:[function(t,e,s){"use strict";var i=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0;var r=t("../util/location"),n=t("./context"),a=t("./types"),o=function(){function t(){i(this,t)}return t.prototype.init=function(t,e){return this.strict=t.strictMode===!1?!1:"module"===t.sourceType,this.input=e,this.potentialArrowAt=-1,this.inMethod=this.inFunction=this.inGenerator=this.inAsync=!1,this.labels=[],this.decorators=[],this.tokens=[],this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.pos=this.lineStart=0,this.curLine=1,this.type=a.types.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=[n.types.b_stat],this.exprAllowed=!0,this.containsEsc=this.containsOctal=!1,this.octalPosition=null,this},t.prototype.curPosition=function(){return new r.Position(this.curLine,this.pos-this.lineStart)},t.prototype.clone=function(e){var s=new t;for(var i in this){var r=this[i];e&&"context"!==i||!Array.isArray(r)||(r=r.slice()),s[i]=r}return s},t}();s["default"]=o,e.exports=s["default"]},{"../util/location":19,"./context":14,"./types":17,"babel-runtime/helpers/class-call-check":24}],17:[function(t,e,s){"use strict";function i(t,e){return new a(t,{beforeExpr:!0,binop:e})}function r(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];e.keyword=t,c[t]=p["_"+t]=new a(t,e)}var n=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0;var a=function l(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];n(this,l),this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop||null,this.updateContext=null};s.TokenType=a;var o={beforeExpr:!0},u={startsExpr:!0},p={num:new a("num",u),regexp:new a("regexp",u),string:new a("string",u),name:new a("name",u),eof:new a("eof"),bracketL:new a("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new a("]"),braceL:new a("{",{beforeExpr:!0,startsExpr:!0}),braceR:new a("}"),parenL:new a("(",{beforeExpr:!0,startsExpr:!0}),parenR:new a(")"),comma:new a(",",o),semi:new a(";",o),colon:new a(":",o),doubleColon:new a("::",o),dot:new a("."),question:new a("?",o),arrow:new a("=>",o),template:new a("template"),ellipsis:new a("...",o),backQuote:new a("`",u),dollarBraceL:new a("${",{beforeExpr:!0,startsExpr:!0}),at:new a("@"),eq:new a("=",{beforeExpr:!0,isAssign:!0}),assign:new a("_=",{beforeExpr:!0,isAssign:!0}),incDec:new a("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new a("prefix",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:i("||",1),logicalAND:i("&&",2),bitwiseOR:i("|",3),bitwiseXOR:i("^",4),bitwiseAND:i("&",5),equality:i("==/!=",6),relational:i("</>",7),bitShift:i("<</>>",8),plusMin:new a("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:i("%",10),star:i("*",10),slash:i("/",10),exponent:new a("**",{beforeExpr:!0,binop:11,rightAssociative:!0})};s.types=p;var c={};s.keywords=c,r("break"),r("case",o),r("catch"),r("continue"),r("debugger"),r("default",o),r("do",{isLoop:!0,beforeExpr:!0}),r("else",o),r("finally"),r("for",{isLoop:!0}),r("function",u),r("if"),r("return",o),r("switch"),r("throw",o),r("try"),r("var"),r("let"),r("const"),r("while",{isLoop:!0}),r("with"),r("new",{beforeExpr:!0,startsExpr:!0}),r("this",u),r("super",u),r("class"),r("extends",o),r("export"),r("import"),r("yield",{beforeExpr:!0,startsExpr:!0}),r("null",u),r("true",u),r("false",u),r("in",{beforeExpr:!0,binop:7}),r("instanceof",{beforeExpr:!0,binop:7}),r("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),r("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),r("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},{"babel-runtime/helpers/class-call-check":24}],18:[function(t,e,s){"use strict";function i(t){return t=t.split(" "),function(e){return t.indexOf(e)>=0}}function r(t,e){for(var s=65536,i=0;i<e.length;i+=2){if(s+=e[i],s>t)return!1;if(s+=e[i+1],s>=t)return!0}}function n(t){return 65>t?36===t:91>t?!0:97>t?95===t:123>t?!0:65535>=t?t>=170&&l.test(String.fromCharCode(t)):r(t,f)}function a(t){return 48>t?36===t:58>t?!0:65>t?!1:91>t?!0:97>t?95===t:123>t?!0:65535>=t?t>=170&&h.test(String.fromCharCode(t)):r(t,f)||r(t,d)}s.__esModule=!0,s.isIdentifierStart=n,s.isIdentifierChar=a;var o={6:i("enum await"),strict:i("implements interface let package private protected public static yield"),strictBind:i("eval arguments")};s.reservedWords=o;var u=i("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super");s.isKeyword=u;var p="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",c="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_",l=new RegExp("["+p+"]"),h=new RegExp("["+p+c+"]"); p=c=null;var f=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,99,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,98,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,955,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,38,17,2,24,133,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,32,4,287,47,21,1,2,0,185,46,82,47,21,0,60,42,502,63,32,0,449,56,1288,920,104,110,2962,1070,13266,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,16481,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,1340,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,16355,541],d=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,16,9,83,11,168,11,6,9,8,2,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,316,19,13,9,214,6,3,8,112,16,16,9,82,12,9,9,535,9,20855,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,4305,6,792618,239]},{}],19:[function(t,e,s){"use strict";function i(t,e){for(var s=1,i=0;;){n.lineBreakG.lastIndex=i;var r=n.lineBreakG.exec(t);if(!(r&&r.index<e))return new a(s,e-i);++s,i=r.index+r[0].length}}var r=t("babel-runtime/helpers/class-call-check")["default"];s.__esModule=!0,s.getLineInfo=i;var n=t("./whitespace"),a=function u(t,e){r(this,u),this.line=t,this.column=e};s.Position=a;var o=function p(t,e){r(this,p),this.start=t,this.end=e};s.SourceLocation=o},{"./whitespace":20,"babel-runtime/helpers/class-call-check":24}],20:[function(t,e,s){"use strict";function i(t){return 10===t||13===t||8232===t||8233===t}s.__esModule=!0,s.isNewLine=i;var r=/\r\n?|\n|\u2028|\u2029/;s.lineBreak=r;var n=new RegExp(r.source,"g");s.lineBreakG=n;var a=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;s.nonASCIIwhitespace=a},{}],21:[function(t,e,s){e.exports={"default":t("core-js/library/fn/get-iterator"),__esModule:!0}},{"core-js/library/fn/get-iterator":27}],22:[function(t,e,s){e.exports={"default":t("core-js/library/fn/object/create"),__esModule:!0}},{"core-js/library/fn/object/create":28}],23:[function(t,e,s){e.exports={"default":t("core-js/library/fn/object/set-prototype-of"),__esModule:!0}},{"core-js/library/fn/object/set-prototype-of":29}],24:[function(t,e,s){"use strict";s["default"]=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},s.__esModule=!0},{}],25:[function(t,e,s){"use strict";var i=t("babel-runtime/core-js/object/create")["default"],r=t("babel-runtime/core-js/object/set-prototype-of")["default"];s["default"]=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=i(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(r?r(t,e):t.__proto__=e)},s.__esModule=!0},{"babel-runtime/core-js/object/create":22,"babel-runtime/core-js/object/set-prototype-of":23}],26:[function(t,e,s){"use strict";s["default"]=function(t){return t&&t.__esModule?t:{"default":t}},s.__esModule=!0},{}],27:[function(t,e,s){t("../modules/web.dom.iterable"),t("../modules/es6.string.iterator"),e.exports=t("../modules/core.get-iterator")},{"../modules/core.get-iterator":63,"../modules/es6.string.iterator":66,"../modules/web.dom.iterable":67}],28:[function(t,e,s){var i=t("../../modules/$");e.exports=function(t,e){return i.create(t,e)}},{"../../modules/$":50}],29:[function(t,e,s){t("../../modules/es6.object.set-prototype-of"),e.exports=t("../../modules/$.core").Object.setPrototypeOf},{"../../modules/$.core":35,"../../modules/es6.object.set-prototype-of":65}],30:[function(t,e,s){e.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},{}],31:[function(t,e,s){e.exports=function(){}},{}],32:[function(t,e,s){var i=t("./$.is-object");e.exports=function(t){if(!i(t))throw TypeError(t+" is not an object!");return t}},{"./$.is-object":45}],33:[function(t,e,s){var i=t("./$.cof"),r=t("./$.wks")("toStringTag"),n="Arguments"==i(function(){return arguments}());e.exports=function(t){var e,s,a;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(s=(e=Object(t))[r])?s:n?i(e):"Object"==(a=i(e))&&"function"==typeof e.callee?"Arguments":a}},{"./$.cof":34,"./$.wks":61}],34:[function(t,e,s){var i={}.toString;e.exports=function(t){return i.call(t).slice(8,-1)}},{}],35:[function(t,e,s){var i=e.exports={version:"1.2.6"};"number"==typeof __e&&(__e=i)},{}],36:[function(t,e,s){var i=t("./$.a-function");e.exports=function(t,e,s){if(i(t),void 0===e)return t;switch(s){case 1:return function(s){return t.call(e,s)};case 2:return function(s,i){return t.call(e,s,i)};case 3:return function(s,i,r){return t.call(e,s,i,r)}}return function(){return t.apply(e,arguments)}}},{"./$.a-function":30}],37:[function(t,e,s){e.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},{}],38:[function(t,e,s){e.exports=!t("./$.fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./$.fails":40}],39:[function(t,e,s){var i=t("./$.global"),r=t("./$.core"),n=t("./$.ctx"),a="prototype",o=function(t,e,s){var u,p,c,l=t&o.F,h=t&o.G,f=t&o.S,d=t&o.P,y=t&o.B,m=t&o.W,v=h?r:r[e]||(r[e]={}),g=h?i:f?i[e]:(i[e]||{})[a];h&&(s=e);for(u in s)p=!l&&g&&u in g,p&&u in v||(c=p?g[u]:s[u],v[u]=h&&"function"!=typeof g[u]?s[u]:y&&p?n(c,i):m&&g[u]==c?function(t){var e=function(e){return this instanceof t?new t(e):t(e)};return e[a]=t[a],e}(c):d&&"function"==typeof c?n(Function.call,c):c,d&&((v[a]||(v[a]={}))[u]=c))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,e.exports=o},{"./$.core":35,"./$.ctx":36,"./$.global":41}],40:[function(t,e,s){e.exports=function(t){try{return!!t()}catch(e){return!0}}},{}],41:[function(t,e,s){var i=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=i)},{}],42:[function(t,e,s){var i={}.hasOwnProperty;e.exports=function(t,e){return i.call(t,e)}},{}],43:[function(t,e,s){var i=t("./$"),r=t("./$.property-desc");e.exports=t("./$.descriptors")?function(t,e,s){return i.setDesc(t,e,r(1,s))}:function(t,e,s){return t[e]=s,t}},{"./$":50,"./$.descriptors":38,"./$.property-desc":52}],44:[function(t,e,s){var i=t("./$.cof");e.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==i(t)?t.split(""):Object(t)}},{"./$.cof":34}],45:[function(t,e,s){e.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},{}],46:[function(t,e,s){"use strict";var i=t("./$"),r=t("./$.property-desc"),n=t("./$.set-to-string-tag"),a={};t("./$.hide")(a,t("./$.wks")("iterator"),function(){return this}),e.exports=function(t,e,s){t.prototype=i.create(a,{next:r(1,s)}),n(t,e+" Iterator")}},{"./$":50,"./$.hide":43,"./$.property-desc":52,"./$.set-to-string-tag":55,"./$.wks":61}],47:[function(t,e,s){"use strict";var i=t("./$.library"),r=t("./$.export"),n=t("./$.redefine"),a=t("./$.hide"),o=t("./$.has"),u=t("./$.iterators"),p=t("./$.iter-create"),c=t("./$.set-to-string-tag"),l=t("./$").getProto,h=t("./$.wks")("iterator"),f=!([].keys&&"next"in[].keys()),d="@@iterator",y="keys",m="values",v=function(){return this};e.exports=function(t,e,s,g,x,A,b){p(s,e,g);var E,C,D=function(t){if(!f&&t in T)return T[t];switch(t){case y:return function(){return new s(this,t)};case m:return function(){return new s(this,t)}}return function(){return new s(this,t)}},S=e+" Iterator",F=x==m,w=!1,T=t.prototype,k=T[h]||T[d]||x&&T[x],P=k||D(x);if(k){var _=l(P.call(new t));c(_,S,!0),!i&&o(T,d)&&a(_,h,v),F&&k.name!==m&&(w=!0,P=function(){return k.call(this)})}if(i&&!b||!f&&!w&&T[h]||a(T,h,P),u[e]=P,u[S]=v,x)if(E={values:F?P:D(m),keys:A?P:D(y),entries:F?D("entries"):P},b)for(C in E)C in T||n(T,C,E[C]);else r(r.P+r.F*(f||w),e,E);return E}},{"./$":50,"./$.export":39,"./$.has":42,"./$.hide":43,"./$.iter-create":46,"./$.iterators":49,"./$.library":51,"./$.redefine":53,"./$.set-to-string-tag":55,"./$.wks":61}],48:[function(t,e,s){e.exports=function(t,e){return{value:e,done:!!t}}},{}],49:[function(t,e,s){e.exports={}},{}],50:[function(t,e,s){var i=Object;e.exports={create:i.create,getProto:i.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:i.getOwnPropertyDescriptor,setDesc:i.defineProperty,setDescs:i.defineProperties,getKeys:i.keys,getNames:i.getOwnPropertyNames,getSymbols:i.getOwnPropertySymbols,each:[].forEach}},{}],51:[function(t,e,s){e.exports=!0},{}],52:[function(t,e,s){e.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},{}],53:[function(t,e,s){e.exports=t("./$.hide")},{"./$.hide":43}],54:[function(t,e,s){var i=t("./$").getDesc,r=t("./$.is-object"),n=t("./$.an-object"),a=function(t,e){if(n(t),!r(e)&&null!==e)throw TypeError(e+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,s,r){try{r=t("./$.ctx")(Function.call,i(Object.prototype,"__proto__").set,2),r(e,[]),s=!(e instanceof Array)}catch(n){s=!0}return function(t,e){return a(t,e),s?t.__proto__=e:r(t,e),t}}({},!1):void 0),check:a}},{"./$":50,"./$.an-object":32,"./$.ctx":36,"./$.is-object":45}],55:[function(t,e,s){var i=t("./$").setDesc,r=t("./$.has"),n=t("./$.wks")("toStringTag");e.exports=function(t,e,s){t&&!r(t=s?t:t.prototype,n)&&i(t,n,{configurable:!0,value:e})}},{"./$":50,"./$.has":42,"./$.wks":61}],56:[function(t,e,s){var i=t("./$.global"),r="__core-js_shared__",n=i[r]||(i[r]={});e.exports=function(t){return n[t]||(n[t]={})}},{"./$.global":41}],57:[function(t,e,s){var i=t("./$.to-integer"),r=t("./$.defined");e.exports=function(t){return function(e,s){var n,a,o=String(r(e)),u=i(s),p=o.length;return 0>u||u>=p?t?"":void 0:(n=o.charCodeAt(u),55296>n||n>56319||u+1===p||(a=o.charCodeAt(u+1))<56320||a>57343?t?o.charAt(u):n:t?o.slice(u,u+2):(n-55296<<10)+(a-56320)+65536)}}},{"./$.defined":37,"./$.to-integer":58}],58:[function(t,e,s){var i=Math.ceil,r=Math.floor;e.exports=function(t){return isNaN(t=+t)?0:(t>0?r:i)(t)}},{}],59:[function(t,e,s){var i=t("./$.iobject"),r=t("./$.defined");e.exports=function(t){return i(r(t))}},{"./$.defined":37,"./$.iobject":44}],60:[function(t,e,s){var i=0,r=Math.random();e.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++i+r).toString(36))}},{}],61:[function(t,e,s){var i=t("./$.shared")("wks"),r=t("./$.uid"),n=t("./$.global").Symbol;e.exports=function(t){return i[t]||(i[t]=n&&n[t]||(n||r)("Symbol."+t))}},{"./$.global":41,"./$.shared":56,"./$.uid":60}],62:[function(t,e,s){var i=t("./$.classof"),r=t("./$.wks")("iterator"),n=t("./$.iterators");e.exports=t("./$.core").getIteratorMethod=function(t){return void 0!=t?t[r]||t["@@iterator"]||n[i(t)]:void 0}},{"./$.classof":33,"./$.core":35,"./$.iterators":49,"./$.wks":61}],63:[function(t,e,s){var i=t("./$.an-object"),r=t("./core.get-iterator-method");e.exports=t("./$.core").getIterator=function(t){var e=r(t);if("function"!=typeof e)throw TypeError(t+" is not iterable!");return i(e.call(t))}},{"./$.an-object":32,"./$.core":35,"./core.get-iterator-method":62}],64:[function(t,e,s){"use strict";var i=t("./$.add-to-unscopables"),r=t("./$.iter-step"),n=t("./$.iterators"),a=t("./$.to-iobject");e.exports=t("./$.iter-define")(Array,"Array",function(t,e){this._t=a(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,s=this._i++;return!t||s>=t.length?(this._t=void 0,r(1)):"keys"==e?r(0,s):"values"==e?r(0,t[s]):r(0,[s,t[s]])},"values"),n.Arguments=n.Array,i("keys"),i("values"),i("entries")},{"./$.add-to-unscopables":31,"./$.iter-define":47,"./$.iter-step":48,"./$.iterators":49,"./$.to-iobject":59}],65:[function(t,e,s){var i=t("./$.export");i(i.S,"Object",{setPrototypeOf:t("./$.set-proto").set})},{"./$.export":39,"./$.set-proto":54}],66:[function(t,e,s){"use strict";var i=t("./$.string-at")(!0);t("./$.iter-define")(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,s=this._i;return s>=e.length?{value:void 0,done:!0}:(t=i(e,s),this._i+=t.length,{value:t,done:!1})})},{"./$.iter-define":47,"./$.string-at":57}],67:[function(t,e,s){t("./es6.array.iterator");var i=t("./$.iterators");i.NodeList=i.HTMLCollection=i.Array},{"./$.iterators":49,"./es6.array.iterator":64}]},{},[1])(1)})},function(t,e,s){(function(t){"use strict";function i(){var t=this.evaluate();return t.confident?!!t.value:void 0}function r(){function e(t){i&&(r=t,i=!1)}function s(r){if(i){var u=r.node;if(r.isSequenceExpression()){var p=r.get("expressions");return s(p[p.length-1])}if(r.isStringLiteral()||r.isNumericLiteral()||r.isBooleanLiteral())return u.value;if(r.isNullLiteral())return null;if(r.isTemplateLiteral()){for(var c="",l=0,p=r.get("expressions"),h=u.quasis,f=Array.isArray(h),d=0,h=f?h:n(h);;){var y;if(f){if(d>=h.length)break;y=h[d++]}else{if(d=h.next(),d.done)break;y=d.value}var m=y;if(!i)break;c+=m.value.cooked;var v=p[l++];v&&(c+=String(s(v)))}if(!i)return;return c}if(r.isConditionalExpression()){var g=s(r.get("test"));if(!i)return;return s(g?r.get("consequent"):r.get("alternate"))}if(r.isExpressionWrapper())return s(r.get("expression"));if(r.isMemberExpression()&&!r.parentPath.isCallExpression({callee:u})){var x=r.get("property"),A=r.get("object");if(A.isLiteral()&&x.isIdentifier()){var b=A.node.value,E=typeof b;if("number"===E||"string"===E)return b[x.node.name]}}if(r.isReferencedIdentifier()){var C=r.scope.getBinding(u.name);if(C&&C.hasValue)return C.value;if("undefined"===u.name)return;if("Infinity"===u.name)return 1/0;if("NaN"===u.name)return NaN;var D=r.resolve();return D===r?e(r):s(D)}if(r.isUnaryExpression({prefix:!0})){if("void"===u.operator)return;var S=r.get("argument");if("typeof"===u.operator&&(S.isFunction()||S.isClass()))return"function";var F=s(S);if(!i)return;switch(u.operator){case"!":return!F;case"+":return+F;case"-":return-F;case"~":return~F;case"typeof":return typeof F}}if(r.isArrayExpression()){for(var w=[],T=r.get("elements"),k=T,P=Array.isArray(k),_=0,k=P?k:n(k);;){var B;if(P){if(_>=k.length)break;B=k[_++]}else{if(_=k.next(),_.done)break;B=_.value}var m=B;if(m=m.evaluate(),!m.confident)return e(m);w.push(m.value)}return w}if(r.isObjectExpression(),r.isLogicalExpression()){var N=i,L=s(r.get("left")),I=i;i=N;var O=s(r.get("right")),M=i;switch(i=I&&M,u.operator){case"||":if(L&&I)return i=!0,L;if(!i)return;return L||O;case"&&":if((!L&&I||!O&&M)&&(i=!0),!i)return;return L&&O}}if(r.isBinaryExpression()){var L=s(r.get("left"));if(!i)return;var O=s(r.get("right"));if(!i)return;switch(u.operator){case"-":return L-O;case"+":return L+O;case"/":return L/O;case"*":return L*O;case"%":return L%O;case"**":return Math.pow(L,O);case"<":return O>L;case">":return L>O;case"<=":return O>=L;case">=":return L>=O;case"==":return L==O;case"!=":return L!=O;case"===":return L===O;case"!==":return L!==O;case"|":return L|O;case"&":return L&O;case"^":return L^O;case"<<":return L<<O;case">>":return L>>O;case">>>":return L>>>O}}if(r.isCallExpression()){var j=r.get("callee"),R=void 0,V=void 0;if(j.isIdentifier()&&!r.scope.getBinding(j.node.name,!0)&&a.indexOf(j.node.name)>=0&&(V=t[u.callee.name]),j.isMemberExpression()){var A=j.get("object"),x=j.get("property");if(A.isIdentifier()&&x.isIdentifier()&&a.indexOf(A.node.name)>=0&&o.indexOf(x.node.name)<0&&(R=t[A.node.name],V=R[x.node.name]),A.isLiteral()&&x.isIdentifier()){var E=typeof A.node.value;("string"===E||"number"===E)&&(R=A.node.value,V=R[x.node.name])}}if(V){var $=r.get("arguments").map(s);if(!i)return;return V.apply(R,$)}}e(r)}}var i=!0,r=void 0,u=s(this);return i||(u=void 0),{confident:i,deopt:r,value:u}}var n=s(54)["default"];e.__esModule=!0,e.evaluateTruthy=i,e.evaluate=r;var a=["String","Number","Math"],o=["random"]}).call(e,function(){return this}())},function(t,e,s){"use strict";function i(){var t=this.node,e=void 0;if(this.isMemberExpression())e=t.property;else{if(!this.isProperty()&&!this.isMethod())throw new ReferenceError("todo");e=t.key}return t.computed||u.isIdentifier(e)&&(e=u.stringLiteral(e.name)),e}function r(){return u.ensureBlock(this.node)}function n(){if(this.isArrowFunctionExpression()){this.ensureBlock();var t=this.node;t.expression=!1,t.type="FunctionExpression",t.shadow=t.shadow||!0}}var a=s(86)["default"];e.__esModule=!0,e.toComputedKey=i,e.ensureBlock=r,e.arrowFunctionToShadowed=n;var o=s(41),u=a(o)},function(t,e,s){"use strict";function i(t,e){function s(t){var e=i[n];return"*"===e||t===e}if(!this.isMemberExpression())return!1;for(var i=t.split("."),r=[this.node],n=0;r.length;){var a=r.shift();if(e&&n===i.length)return!0;if(S.isIdentifier(a)){if(!s(a.name))return!1}else if(S.isLiteral(a)){if(!s(a.value))return!1}else{if(S.isMemberExpression(a)){if(a.computed&&!S.isLiteral(a.property))return!1;r.unshift(a.property),r.unshift(a.object);continue}if(!S.isThisExpression(a))return!1;if(!s("this"))return!1}if(++n>i.length)return!1}return n===i.length}function r(t){var e=this.node&&this.node[t];return e&&Array.isArray(e)?!!e.length:!!e}function n(){return this.scope.isStatic(this.node)}function a(t){return!this.has(t)}function o(t,e){return this.node[t]===e}function u(t){return S.isType(this.type,t)}function p(){return("init"===this.key||"left"===this.key)&&this.parentPath.isFor()}function c(t){var e=this,s=!0;do{var i=e.container;if(e.isFunction()&&!s)return!!t;if(s=!1,Array.isArray(i)&&e.key!==i.length-1)return!1}while((e=e.parentPath)&&!e.isProgram());return!0}function l(){return this.parentPath.isLabeledStatement()||S.isBlockStatement(this.container)?!1:C["default"](S.STATEMENT_OR_BLOCK_KEYS,this.key)}function h(t,e){if(!this.isReferencedIdentifier())return!1;var s=this.scope.getBinding(this.node.name);if(!s||"module"!==s.kind)return!1;var i=s.path,r=i.parentPath;return r.isImportDeclaration()?r.node.source.value!==t?!1:e?i.isImportDefaultSpecifier()&&"default"===e?!0:i.isImportNamespaceSpecifier()&&"*"===e?!0:i.isImportSpecifier()&&i.node.imported.name===e?!0:!1:!0:!1}function f(){var t=this.node;return t.end?this.hub.file.code.slice(t.start,t.end):""}function d(t){return"after"!==this._guessExecutionStatusRelativeTo(t)}function y(t){var e=t.scope.getFunctionParent(),s=this.scope.getFunctionParent();if(e.node!==s.node){var i=this._guessExecutionStatusRelativeToDifferentFunctions(e);if(i)return i;t=e.path}var r=t.getAncestry();if(r.indexOf(this)>=0)return"after";var n=this.getAncestry(),a=void 0,o=void 0,u=void 0;for(u=0;u<n.length;u++){var p=n[u];if(o=r.indexOf(p),o>=0){a=p;break}}if(!a)return"before";var c=r[o-1],l=n[u-1];if(!c||!l)return"before";if(c.listKey&&c.container===l.container)return c.key>l.key?"before":"after";var h=S.VISITOR_KEYS[c.type].indexOf(c.key),f=S.VISITOR_KEYS[l.type].indexOf(l.key);return h>f?"before":"after"}function m(t){var e=t.path;if(e.isFunctionDeclaration()){var s=e.scope.getBinding(e.node.id.name);if(!s.references)return"before";for(var i=s.referencePaths,r=i,n=Array.isArray(r),a=0,r=n?r:x(r);;){var o;if(n){if(a>=r.length)break;o=r[a++]}else{if(a=r.next(),a.done)break;o=a.value}var u=o;if("callee"!==u.key||!u.parentPath.isCallExpression())return}for(var p=void 0,c=i,l=Array.isArray(c),h=0,c=l?c:x(c);;){var f;if(l){if(h>=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}var u=f,d=!!u.find(function(t){return t.node===e.node});if(!d){var y=this._guessExecutionStatusRelativeTo(u);if(p){if(p!==y)return}else p=y}}return p}}function v(t,e){return this._resolve(t,e)||this}function g(t,e){var s=this;if(!(e&&e.indexOf(this)>=0))if(e=e||[],e.push(this),this.isVariableDeclarator()){if(this.get("id").isIdentifier())return this.get("init").resolve(t,e)}else if(this.isReferencedIdentifier()){var i=this.scope.getBinding(this.node.name);if(!i)return;if(!i.constant)return;if("module"===i.kind)return;if(i.path!==this){var r=function(){var r=i.path.resolve(t,e);return s.find(function(t){return t.node===r.node})?{v:void 0}:{v:r}}();if("object"==typeof r)return r.v}}else{if(this.isTypeCastExpression())return this.get("expression").resolve(t,e);if(t&&this.isMemberExpression()){var n=this.toComputedKey();if(!S.isLiteral(n))return;var a=n.value,o=this.get("object").resolve(t,e);if(o.isObjectExpression())for(var u=o.get("properties"),p=u,c=Array.isArray(p),l=0,p=c?p:x(p);;){var h;if(c){if(l>=p.length)break;h=p[l++]}else{if(l=p.next(),l.done)break;h=l.value}var f=h;if(f.isProperty()){var d=f.get("key"),y=f.isnt("computed")&&d.isIdentifier({name:a});if(y=y||d.isLiteral({value:a}))return f.get("value").resolve(t,e)}}else if(o.isArrayExpression()&&!isNaN(+a)){var m=o.get("elements"),v=m[a];if(v)return v.resolve(t,e)}}}}var x=s(54)["default"],A=s(85)["default"],b=s(86)["default"];e.__esModule=!0,e.matchesPattern=i,e.has=r,e.isStatic=n,e.isnt=a,e.equals=o,e.isNodeType=u,e.canHaveVariableDeclarationOrExpression=p,e.isCompletionRecord=c,e.isStatementOrBlock=l,e.referencesImport=h,e.getSource=f,e.willIMaybeExecuteBefore=d,e._guessExecutionStatusRelativeTo=y,e._guessExecutionStatusRelativeToDifferentFunctions=m,e.resolve=v,e._resolve=g;var E=s(223),C=A(E),D=s(41),S=b(D),F=r;e.is=F},function(t,e,s){"use strict";function i(t){var e=this.opts;return this.debug(function(){return t}),this.node&&this._call(e[t])?!0:this.node?this._call(e[this.node.type]&&e[this.node.type][t]):!1}function r(t){if(!t)return!1;for(var e=t,s=Array.isArray(e),i=0,e=s?e:E(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var n=r;if(n){var a=this.node;if(!a)return!0;var o=n.call(this.state,this,this.state);if(o)throw new Error("Unexpected return value from visitor method "+n);if(this.node!==a)return!0;if(this.shouldStop||this.shouldSkip||this.removed)return!0}}return!1}function n(){var t=this.opts.blacklist;return t&&t.indexOf(this.node.type)>-1}function a(){return this.node?this.isBlacklisted()?!1:this.opts.shouldSkip&&this.opts.shouldSkip(this)?!1:this.call("enter")||this.shouldSkip?(this.debug(function(){return"Skip..."}),this.shouldStop):(this.debug(function(){return"Recursing into..."}),S["default"].node(this.node,this.opts,this.scope,this.state,this,this.skipKeys),this.call("exit"),this.shouldStop):!1}function o(){this.shouldSkip=!0}function u(t){this.skipKeys[t]=!0}function p(){this.shouldStop=!0,this.shouldSkip=!0}function c(){if(!this.opts||!this.opts.noScope){var t=this.context&&this.context.scope;if(!t)for(var e=this.parentPath;e&&!t;){if(e.opts&&e.opts.noScope)return;t=e.scope,e=e.parentPath}this.scope=this.getScope(t),this.scope&&this.scope.init()}}function l(t){return this.shouldSkip=!1,this.shouldStop=!1,this.removed=!1,this.skipKeys={},t&&(this.context=t,this.state=t.state,this.opts=t.opts),this.setScope(),this}function h(){this.removed||(this._resyncParent(),this._resyncList(),this._resyncKey())}function f(){this.parentPath&&(this.parent=this.parentPath.node)}function d(){if(this.container&&this.node!==this.container[this.key]){if(Array.isArray(this.container)){for(var t=0;t<this.container.length;t++)if(this.container[t]===this.node)return this.setKey(t)}else for(var e in this.container)if(this.container[e]===this.node)return this.setKey(e);this.key=null}}function y(){if(this.parent&&this.inList){var t=this.parent[this.listKey];this.container!==t&&(this.container=t||null)}}function m(){null!=this.key&&this.container&&this.container[this.key]===this.node||this._markRemoved()}function v(){this.contexts.pop(),this.setContext(this.contexts[this.contexts.length-1])}function g(t){this.contexts.push(t),this.setContext(t)}function x(t,e,s,i){this.inList=!!s,this.listKey=s,this.parentKey=s||i,this.container=e,this.parentPath=t||this.parentPath,this.setKey(i)}function A(t){this.key=t,this.node=this.container[this.key],this.type=this.node&&this.node.type}function b(){var t=arguments.length<=0||void 0===arguments[0]?this:arguments[0];if(!t.removed)for(var e=this.contexts,s=Array.isArray(e),i=0,e=s?e:E(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var n=r;n.maybeQueue(t)}}var E=s(54)["default"],C=s(85)["default"];e.__esModule=!0,e.call=i,e._call=r,e.isBlacklisted=n,e.visit=a,e.skip=o,e.skipKey=u,e.stop=p,e.setScope=c,e.setContext=l,e.resync=h,e._resyncParent=f,e._resyncKey=d,e._resyncList=y,e._resyncRemoved=m,e.popContext=v,e.pushContext=g,e.setup=x,e.setKey=A,e.requeue=b;var D=s(201),S=C(D)},function(t,e,s){"use strict";function i(){return this._assertUnremoved(),this.resync(),this._callRemovalHooks()?void this._markRemoved():(this.shareCommentsWithSiblings(),this._remove(),void this._markRemoved())}function r(){for(var t=p.hooks,e=Array.isArray(t),s=0,t=e?t:u(t);;){var i;if(e){if(s>=t.length)break;i=t[s++]}else{if(s=t.next(),s.done)break;i=s.value}var r=i;if(r(this,this.parentPath))return!0}}function n(){Array.isArray(this.container)?(this.container.splice(this.key,1),this.updateSiblingKeys(this.key,-1)):this._replaceWith(null)}function a(){this.shouldSkip=!0,this.removed=!0,this.node=null}function o(){if(this.removed)throw this.buildCodeFrameError("NodePath has been removed so is read-only.")}var u=s(54)["default"];e.__esModule=!0,e.remove=i,e._callRemovalHooks=r,e._remove=n,e._markRemoved=a,e._assertUnremoved=o;var p=s(264)},function(t,e){"use strict";e.__esModule=!0;var s=[function(t,e){return"body"===t.key&&e.isArrowFunctionExpression()?(t.replaceWith(t.scope.buildUndefinedNode()),!0):void 0},function(t,e){var s=!1;return s=s||"test"===t.key&&(e.isWhile()||e.isSwitchCase()),s=s||"declaration"===t.key&&e.isExportDeclaration(),s=s||"body"===t.key&&e.isLabeledStatement(),s=s||"declarations"===t.listKey&&e.isVariableDeclaration()&&1===e.node.declarations.length,s=s||"expression"===t.key&&e.isExpressionStatement(),s?(e.remove(),!0):void 0},function(t,e){return e.isSequenceExpression()&&1===e.node.expressions.length?(e.replaceWith(e.node.expressions[0]),!0):void 0},function(t,e){return e.isBinary()?("left"===t.key?e.replaceWith(e.node.right):e.replaceWith(e.node.left),!0):void 0}];e.hooks=s},function(t,e,s){"use strict";function i(t){if(this._assertUnremoved(),t=this._verifyNodeList(t),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertBefore(t);if(this.isNodeType("Expression")||this.parentPath.isForStatement()&&"init"===this.key)this.node&&t.push(this.node),this.replaceExpressionWithStatements(t);else{if(this._maybePopFromStatements(t),Array.isArray(this.container))return this._containerInsertBefore(t);if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&t.push(this.node),this._replaceWith(C.blockStatement(t))}return[this]}function r(t,e){this.updateSiblingKeys(t,e.length);for(var s=[],i=0;i<e.length;i++){var r=t+i,n=e[i];if(this.container.splice(r,0,n),this.context){var a=this.context.create(this.parent,this.container,r,this.listKey);s.push(a)}else s.push(b["default"].get({parentPath:this.parentPath,parent:this.parent,container:this.container,listKey:this.listKey,key:r}))}for(var o=this.contexts,u=this;!o.length;)u=u.parentPath,o=u.contexts;for(var p=s,c=Array.isArray(p),l=0,p=c?p:d(p);;){var h;if(c){if(l>=p.length)break;h=p[l++]}else{if(l=p.next(),l.done)break;h=l.value}var f=h;f.setScope(),f.debug(function(){return"Inserted."});for(var y=o,m=Array.isArray(y),v=0,y=m?y:d(y);;){var g;if(m){if(v>=y.length)break;g=y[v++]}else{if(v=y.next(),v.done)break;g=v.value}var x=g;x.maybeQueue(f,!0)}}return s}function n(t){return this._containerInsert(this.key,t)}function a(t){return this._containerInsert(this.key+1,t)}function o(t){var e=t[t.length-1],s=C.isIdentifier(e)||C.isExpressionStatement(e)&&C.isIdentifier(e.expression);s&&!this.isCompletionRecord()&&t.pop()}function u(t){if(this._assertUnremoved(),t=this._verifyNodeList(t),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertAfter(t);if(this.isNodeType("Expression")||this.parentPath.isForStatement()&&"init"===this.key){if(this.node){var e=this.scope.generateDeclaredUidIdentifier();t.unshift(C.expressionStatement(C.assignmentExpression("=",e,this.node))),t.push(C.expressionStatement(e))}this.replaceExpressionWithStatements(t)}else{if(this._maybePopFromStatements(t),Array.isArray(this.container))return this._containerInsertAfter(t);if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&t.unshift(this.node),this._replaceWith(C.blockStatement(t))}return[this]}function p(t,e){if(this.parent)for(var s=this.parent[v.PATH_CACHE_KEY],i=0;i<s.length;i++){var r=s[i];r.key>=t&&(r.key+=e)}}function c(t){if(!t)return[];t.constructor!==Array&&(t=[t]);for(var e=0;e<t.length;e++){var s=t[e],i=void 0;if(s?"object"!=typeof s?i="contains a non-object node":s.type?s instanceof b["default"]&&(i="has a NodePath when it expected a raw object"):i="without a type":i="has falsy node",i){var r=Array.isArray(s)?"array":typeof s;throw new Error("Node list "+i+" with the index of "+e+" and type of "+r)}}return t}function l(t,e){this._assertUnremoved(),e=this._verifyNodeList(e);var s=b["default"].get({parentPath:this,parent:this.node,container:this.node[t],listKey:t,key:0});return s.insertBefore(e)}function h(t,e){this._assertUnremoved(),e=this._verifyNodeList(e);var s=this.node[t],i=b["default"].get({parentPath:this,parent:this.node,container:s,listKey:t,key:s.length});return i.replaceWithMultiple(e)}function f(){var t=arguments.length<=0||void 0===arguments[0]?this.scope:arguments[0],e=new x["default"](this,t);return e.run()}var d=s(54)["default"],y=s(85)["default"],m=s(86)["default"];e.__esModule=!0,e.insertBefore=i,e._containerInsert=r,e._containerInsertBefore=n,e._containerInsertAfter=a,e._maybePopFromStatements=o,e.insertAfter=u,e.updateSiblingKeys=p,e._verifyNodeList=c,e.unshiftContainer=l,e.pushContainer=h,e.hoist=f;var v=s(213),g=s(266),x=y(g),A=s(208),b=y(A),E=s(41),C=m(E)},function(t,e,s){"use strict";var i=s(207)["default"],r=s(54)["default"],n=s(86)["default"];e.__esModule=!0;var a=s(41),o=n(a),u={ReferencedIdentifier:function(t,e){if(!t.isJSXIdentifier()||!a.react.isCompatTag(t.node.name)){var s=t.scope.getBinding(t.node.name);if(s&&s===e.scope.getBinding(t.node.name))if(s.constant)e.bindings[t.node.name]=s;else for(var i=s.constantViolations,n=Array.isArray(i),o=0,i=n?i:r(i);;){var u;if(n){if(o>=i.length)break;u=i[o++]}else{if(o=i.next(),o.done)break;u=o.value}var p=u;e.breakOnScopePaths=e.breakOnScopePaths.concat(p.getAncestry())}}}},p=function(){function t(e,s){i(this,t),this.breakOnScopePaths=[],this.bindings={},this.scopes=[],this.scope=s,this.path=e}return t.prototype.isCompatibleScope=function(t){for(var e in this.bindings){var s=this.bindings[e];if(!t.bindingIdentifierEquals(e,s.identifier))return!1}return!0},t.prototype.getCompatibleScopes=function(){var t=this.path.scope;do{if(!this.isCompatibleScope(t))break;if(this.scopes.push(t),this.breakOnScopePaths.indexOf(t.path)>=0)break}while(t=t.parent)},t.prototype.getAttachmentPath=function(){var t=this.scopes,e=t.pop();if(e){if(e.path.isFunction()){if(this.hasOwnParamBindings(e)){if(this.scope===e)return;return e.path.get("body").get("body")[0]}return this.getNextScopeStatementParent()}return e.path.isProgram()?this.getNextScopeStatementParent():void 0}},t.prototype.getNextScopeStatementParent=function(){var t=this.scopes.pop();return t?t.path.getStatementParent():void 0},t.prototype.hasOwnParamBindings=function(t){for(var e in this.bindings)if(t.hasOwnBinding(e)){var s=this.bindings[e];if("param"===s.kind)return!0}return!1},t.prototype.run=function(){var t=this.path.node;if(!t._hoisted){t._hoisted=!0,this.path.traverse(u,this),this.getCompatibleScopes();var e=this.getAttachmentPath();if(e&&e.getFunctionParent()!==this.path.getFunctionParent()){var s=e.scope.generateUidIdentifier("ref");e.insertBefore([o.variableDeclaration("var",[o.variableDeclarator(s,this.path.node)])]); var i=this.path.parentPath;i.isJSXElement()&&this.path.container===i.node.children&&(s=o.JSXExpressionContainer(s)),this.path.replaceWith(s)}}},t}();e["default"]=p,t.exports=e["default"]},function(t,e,s){"use strict";function i(){var t=this;do{if(!t.parentPath||Array.isArray(t.container)&&t.isStatement())break;t=t.parentPath}while(t);if(t&&(t.isProgram()||t.isFile()))throw new Error("File/Program node, we can't possibly find a statement parent to this");return t}function r(){return"left"===this.key?this.getSibling("right"):"right"===this.key?this.getSibling("left"):void 0}function n(){var t=[],e=function(e){e&&(t=t.concat(e.getCompletionRecords()))};if(this.isIfStatement())e(this.get("consequent")),e(this.get("alternate"));else if(this.isDoExpression()||this.isFor()||this.isWhile())e(this.get("body"));else if(this.isProgram()||this.isBlockStatement())e(this.get("body").pop());else{if(this.isFunction())return this.get("body").getCompletionRecords();this.isTryStatement()?(e(this.get("block")),e(this.get("handler")),e(this.get("finalizer"))):t.push(this)}return t}function a(t){return m["default"].get({parentPath:this.parentPath,parent:this.parent,container:this.container,listKey:this.listKey,key:t})}function o(t,e){e===!0&&(e=this.context);var s=t.split(".");return 1===s.length?this._getKey(t,e):this._getPattern(s,e)}function u(t,e){var s=this,i=this.node,r=i[t];return Array.isArray(r)?r.map(function(n,a){return m["default"].get({listKey:t,parentPath:s,parent:i,container:r,key:a}).setContext(e)}):m["default"].get({parentPath:this,parent:i,container:i,key:t}).setContext(e)}function p(t,e){for(var s=this,i=t,r=Array.isArray(i),n=0,i=r?i:h(i);;){var a;if(r){if(n>=i.length)break;a=i[n++]}else{if(n=i.next(),n.done)break;a=n.value}var o=a;s="."===o?s.parentPath:Array.isArray(s)?s[o]:s.get(o,e)}return s}function c(t){return g.getBindingIdentifiers(this.node,t)}function l(t){return g.getOuterBindingIdentifiers(this.node,t)}var h=s(54)["default"],f=s(85)["default"],d=s(86)["default"];e.__esModule=!0,e.getStatementParent=i,e.getOpposite=r,e.getCompletionRecords=n,e.getSibling=a,e.get=o,e._getKey=u,e._getPattern=p,e.getBindingIdentifiers=c,e.getOuterBindingIdentifiers=l;var y=s(208),m=f(y),v=s(41),g=d(v)},function(t,e){"use strict";function s(){var t=this.node;if(t){var e=t.trailingComments,s=t.leadingComments;if(e||s){var i=this.getSibling(this.key-1),r=this.getSibling(this.key+1);i.node||(i=r),r.node||(r=i),i.addComments("trailing",s),r.addComments("leading",e)}}}function i(t,e,s){this.addComments(t,[{type:s?"CommentLine":"CommentBlock",value:e}])}function r(t,e){if(e){var s=this.node;if(s){var i=t+"Comments";s[i]?s[i]=s[i].concat(e):s[i]=e}}}e.__esModule=!0,e.shareCommentsWithSiblings=s,e.addComment=i,e.addComments=r},function(t,e,s){"use strict";function i(t){if(t._exploded)return t;t._exploded=!0;for(var e in t)if(!l(e)){var s=e.split("|");if(1!==s.length){var i=t[e];delete t[e];for(var n=s,a=Array.isArray(n),o=0,n=a?n:f(n);;){var y;if(a){if(o>=n.length)break;y=n[o++]}else{if(o=n.next(),o.done)break;y=o.value}var m=y;t[m]=i}}}r(t),delete t.__esModule,u(t),p(t);for(var v=d(t),x=Array.isArray(v),A=0,v=x?v:f(v);;){var b;if(x){if(A>=v.length)break;b=v[A++]}else{if(A=v.next(),A.done)break;b=A.value}var e=b;if(!l(e)){var C=g[e];if(C){var i=t[e];for(var S in i)i[S]=c(C,i[S]);if(delete t[e],C.types)for(var F=C.types,w=Array.isArray(F),T=0,F=w?F:f(F);;){var k;if(w){if(T>=F.length)break;k=F[T++]}else{if(T=F.next(),T.done)break;k=T.value}var S=k;t[S]?h(t[S],i):t[S]=i}else h(t,i)}}}for(var e in t)if(!l(e)){var i=t[e],P=E.FLIPPED_ALIAS_KEYS[e],_=E.DEPRECATED_KEYS[e];if(_&&(console.trace("Visitor defined for "+e+" but it has been renamed to "+_),P=[_]),P){delete t[e];for(var B=P,N=Array.isArray(B),L=0,B=N?B:f(B);;){var I;if(N){if(L>=B.length)break;I=B[L++]}else{if(L=B.next(),L.done)break;I=L.value}var O=I,M=t[O];M?h(M,i):t[O]=D["default"](i)}}}for(var e in t)l(e)||p(t[e]);return t}function r(t){if(!t._verified){if("function"==typeof t)throw new Error(A.get("traverseVerifyRootFunction"));for(var e in t)if(("enter"===e||"exit"===e)&&n(e,t[e]),!l(e)){if(E.TYPES.indexOf(e)<0)throw new Error(A.get("traverseVerifyNodeType",e));var s=t[e];if("object"==typeof s)for(var i in s){if("enter"!==i&&"exit"!==i)throw new Error(A.get("traverseVerifyVisitorProperty",e,i));n(e+"."+i,s[i])}}t._verified=!0}}function n(t,e){for(var s=[].concat(e),i=s,r=Array.isArray(i),n=0,i=r?i:f(i);;){var a;if(r){if(n>=i.length)break;a=i[n++]}else{if(n=i.next(),n.done)break;a=n.value}var o=a;if("function"!=typeof o)throw new TypeError("Non-function found defined in "+t+" with type "+typeof o)}}function a(t){for(var e=arguments.length<=1||void 0===arguments[1]?[]:arguments[1],s={},r=0;r<t.length;r++){var n=t[r],a=e[r];i(n);for(var u in n){var p=n[u];a&&(p=o(p,a));var c=s[u]=s[u]||{};h(c,p)}}return s}function o(t,e){var s={};for(var i in t){var r=t[i];Array.isArray(r)&&(r=r.map(function(t){var s=function(s){return t.call(e,s,e)};return s.toString=function(){return t.toString()},s}),s[i]=r)}return s}function u(t){for(var e in t)if(!l(e)){var s=t[e];"function"==typeof s&&(t[e]={enter:s})}}function p(t){t.enter&&!Array.isArray(t.enter)&&(t.enter=[t.enter]),t.exit&&!Array.isArray(t.exit)&&(t.exit=[t.exit])}function c(t,e){var s=function(s){return t.checkPath(s)?e.apply(this,arguments):void 0};return s.toString=function(){return e.toString()},s}function l(t){return"_"===t[0]?!0:"enter"===t||"exit"===t||"shouldSkip"===t?!0:"blacklist"===t||"noScope"===t||"skipKeys"===t?!0:!1}function h(t,e){for(var s in e)t[s]=[].concat(t[s]||[],e[s])}var f=s(54)["default"],d=s(42)["default"],y=s(86)["default"],m=s(85)["default"];e.__esModule=!0,e.explode=i,e.verify=r,e.merge=a;var v=s(209),g=y(v),x=s(234),A=y(x),b=s(41),E=y(b),C=s(100),D=m(C)},function(t,e,s){"use strict";var i=s(207)["default"];e.__esModule=!0;var r=function n(t,e){i(this,n),this.file=t,this.options=e};e["default"]=r,t.exports=e["default"]},function(t,e,s){"use strict";function i(t){var e=r(t);return 1===e.length?e[0]:u.unionTypeAnnotation(e)}function r(t){for(var e={},s={},i=[],n=[],a=0;a<t.length;a++){var o=t[a];if(o&&!(n.indexOf(o)>=0)){if(u.isAnyTypeAnnotation(o))return[o];if(u.isFlowBaseAnnotation(o))s[o.type]=o;else if(u.isUnionTypeAnnotation(o))i.indexOf(o.types)<0&&(t=t.concat(o.types),i.push(o.types));else if(u.isGenericTypeAnnotation(o)){var p=o.id.name;if(e[p]){var c=e[p];c.typeParameters?o.typeParameters&&(c.typeParameters.params=r(c.typeParameters.params.concat(o.typeParameters.params))):c=o.typeParameters}else e[p]=o}else n.push(o)}}for(var l in s)n.push(s[l]);for(var h in e)n.push(e[h]);return n}function n(t){if("string"===t)return u.stringTypeAnnotation();if("number"===t)return u.numberTypeAnnotation();if("undefined"===t)return u.voidTypeAnnotation();if("boolean"===t)return u.booleanTypeAnnotation();if("function"===t)return u.genericTypeAnnotation(u.identifier("Function"));if("object"===t)return u.genericTypeAnnotation(u.identifier("Object"));if("symbol"===t)return u.genericTypeAnnotation(u.identifier("Symbol"));throw new Error("Invalid typeof value")}var a=s(86)["default"];e.__esModule=!0,e.createUnionTypeAnnotation=i,e.removeTypeDuplicates=r,e.createTypeAnnotationBasedOnTypeof=n;var o=s(41),u=a(o)},function(t,e,s){"use strict";var i=s(21)["default"];e.__esModule=!0;var r=function(){function t(){i(this,t),this.line=1,this.column=0}return t.prototype.push=function(t){for(var e=0;e<t.length;e++)"\n"===t[e]?(this.line++,this.column=0):this.column++},t.prototype.unshift=function(t){for(var e=0;e<t.length;e++)"\n"===t[e]?this.line--:this.column--},t}();e["default"]=r,t.exports=e["default"]},function(t,e,s){"use strict";function i(t){for(var e=arguments.length,s=Array(e>1?e-1:0),i=1;e>i;i++)s[i-1]=arguments[i];var n=u[t];if(!n)throw new ReferenceError("Unknown message "+JSON.stringify(t));return s=r(s),n.replace(/\$(\d+)/g,function(t,e){return s[e-1]})}function r(t){return t.map(function(t){if(null!=t&&t.inspect)return t.inspect();try{return JSON.stringify(t)||t+""}catch(e){return o.inspect(t)}})}var n=s(23)["default"];e.__esModule=!0,e.get=i,e.parseArgs=r;var a=s(235),o=n(a),u={tailCallReassignmentDeopt:"Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence",classesIllegalBareSuper:"Illegal use of bare super",classesIllegalSuperCall:"Direct super call is illegal in non-constructor, use super.$1() instead",scopeDuplicateDeclaration:"Duplicate declaration $1",settersNoRest:"Setters aren't allowed to have a rest",noAssignmentsInForHead:"No assignments allowed in for-in/of head",expectedMemberExpressionOrIdentifier:"Expected type MemberExpression or Identifier",invalidParentForThisNode:"We don't know how to handle this node within the current parent - please open an issue",readOnly:"$1 is read-only",unknownForHead:"Unknown node type $1 in ForStatement",didYouMean:"Did you mean $1?",codeGeneratorDeopt:"Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",missingTemplatesDirectory:"no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",unsupportedOutputType:"Unsupported output type $1",illegalMethodName:"Illegal method name $1",lostTrackNodePath:"We lost track of this node's position, likely because the AST was directly manipulated",modulesIllegalExportName:"Illegal export $1",modulesDuplicateDeclarations:"Duplicate module declarations with the same source but in different scopes",undeclaredVariable:"Reference to undeclared variable $1",undeclaredVariableType:"Referencing a type alias outside of a type annotation",undeclaredVariableSuggestion:"Reference to undeclared variable $1 - did you mean $2?",traverseNeedsParent:"You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.",traverseVerifyRootFunction:"You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?",traverseVerifyVisitorProperty:"You passed `traverse()` a visitor object with the property $1 that has the invalid property $2",traverseVerifyNodeType:"You gave us a visitor for the node type $1 but it's not a valid type",pluginNotObject:"Plugin $2 specified in $1 was expected to return an object when invoked but returned $3",pluginNotFunction:"Plugin $2 specified in $1 was expected to return a function but returned $3",pluginUnknown:"Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4",pluginInvalidProperty:"Plugin $2 specified in $1 provided an invalid property of $3"};e.MESSAGES=u},function(t,e,s){"use strict";var i=s(6)["default"],r=s(21)["default"],n=s(275)["default"],a=s(305)["default"],o=s(22)["default"],u=s(23)["default"];e.__esModule=!0;var p=s(25),c=o(p),l=s(310),h=o(l),f=s(312),d=o(f),y=s(41),m=u(y),v=function(t){function e(){r(this,e);for(var s=arguments.length,i=Array(s),n=0;s>n;n++)i[n]=arguments[n];t.call.apply(t,[this].concat(i)),this.insideAux=!1,this.printAuxAfterOnNextUserNode=!1,this._printStack=[]}return i(e,t),e.prototype.print=function(t,e){var s=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];if(t){this._lastPrintedIsEmptyStatement=!1,e&&e._compact&&(t._compact=!0);var i=this.insideAux;this.insideAux=!t.loc;var r=this.format.concise;t._compact&&(this.format.concise=!0);var n=this[t.type];if(!n)throw new ReferenceError("unknown node of type "+JSON.stringify(t.type)+" with constructor "+JSON.stringify(t&&t.constructor.name));this._printStack.push(t),t.loc&&this.printAuxAfterComment(),this.printAuxBeforeComment(i);var a=d["default"].needsParens(t,e,this._printStack);a&&this.push("("),this.printLeadingComments(t,e),this.catchUp(t),this._printNewline(!0,t,e,s),s.before&&s.before(),this.map.mark(t),this._print(t,e),t.loc&&this.printAuxAfterComment(),this.printTrailingComments(t,e),a&&this.push(")"),this._printStack.pop(),e&&this.map.mark(e),s.after&&s.after(),this.format.concise=r,this.insideAux=i,this._printNewline(!1,t,e,s)}},e.prototype.printAuxBeforeComment=function(t){var e=this.format.auxiliaryCommentBefore;t||!this.insideAux||this.printAuxAfterOnNextUserNode||(this.printAuxAfterOnNextUserNode=!0,e&&this.printComment({type:"CommentBlock",value:e}))},e.prototype.printAuxAfterComment=function(){if(this.printAuxAfterOnNextUserNode){this.printAuxAfterOnNextUserNode=!1;var t=this.format.auxiliaryCommentAfter;t&&this.printComment({type:"CommentBlock",value:t})}},e.prototype.getPossibleRaw=function(t){var e=t.extra;return e&&null!=e.raw&&null!=e.rawValue&&t.value===e.rawValue?e.raw:void 0},e.prototype._print=function(t,e){if(!this.format.minified){var s=this.getPossibleRaw(t);if(s)return this.push(""),void this._push(s)}var i=this[t.type];i.call(this,t,e)},e.prototype.printJoin=function(t,e){var s=this,i=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];if(t&&t.length){var r=t.length,n=void 0,a=void 0;i.indent&&this.indent();var o={statement:i.statement,addNewlines:i.addNewlines,after:function(){i.iterator&&i.iterator(n,a),i.separator&&e.loc&&s.printAuxAfterComment(),i.separator&&r-1>a&&s.push(i.separator)}};for(a=0;a<t.length;a++)n=t[a],this.print(n,e,o);i.indent&&this.dedent()}},e.prototype.printAndIndentOnComments=function(t,e){var s=!!t.leadingComments;s&&this.indent(),this.print(t,e),s&&this.dedent()},e.prototype.printBlock=function(t){var e=t.body;m.isEmptyStatement(e)||this.space(),this.print(e,t)},e.prototype.generateComment=function(t){var e=t.value;return e="CommentLine"===t.type?"//"+e:"/*"+e+"*/"},e.prototype.printTrailingComments=function(t,e){this.printComments(this.getComments("trailingComments",t,e))},e.prototype.printLeadingComments=function(t,e){this.printComments(this.getComments("leadingComments",t,e))},e.prototype.printInnerComments=function(t){var e=arguments.length<=1||void 0===arguments[1]?!0:arguments[1];t.innerComments&&(e&&this.indent(),this.printComments(t.innerComments),e&&this.dedent())},e.prototype.printSequence=function(t,e){var s=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return s.statement=!0,this.printJoin(t,e,s)},e.prototype.printList=function(t,e){var s=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return null==s.separator&&(s.separator=",",this.format.compact||(s.separator+=" ")),this.printJoin(t,e,s)},e.prototype._printNewline=function(t,e,s,i){if(i.statement||d["default"].isUserWhitespacable(e,s)){var r=0;if(null!=e.start&&!e._ignoreUserWhitespace&&this.tokens.length)r=t?this.whitespace.getNewlinesBefore(e):this.whitespace.getNewlinesAfter(e);else{t||r++,i.addNewlines&&(r+=i.addNewlines(t,e)||0);var n=d["default"].needsWhitespaceAfter;t&&(n=d["default"].needsWhitespaceBefore),n(e,s)&&r++,this.buf||(r=0)}this.newline(r)}},e.prototype.getComments=function(t,e){return e&&e[t]||[]},e.prototype.shouldPrintComment=function(t){return this.format.shouldPrintComment?this.format.shouldPrintComment(t.value):!this.format.minified&&(t.value.indexOf("@license")>=0||t.value.indexOf("@preserve")>=0)?!0:this.format.comments},e.prototype.printComment=function(t){if(this.shouldPrintComment(t)&&!t.ignore){if(t.ignore=!0,null!=t.start){if(this.printedCommentStarts[t.start])return;this.printedCommentStarts[t.start]=!0}this.catchUp(t),this.newline(this.whitespace.getNewlinesBefore(t));var e=this.position.column,s=this.generateComment(t);if(e&&!this.isLast(["\n"," ","[","{"])&&(this._push(" "),e++),"CommentBlock"===t.type&&this.format.indent.adjustMultilineComment){var i=t.loc&&t.loc.start.column;if(i){var r=new RegExp("\\n\\s{1,"+i+"}","g");s=s.replace(r,"\n")}var n=Math.max(this.indentSize(),e);s=s.replace(/\n/g,"\n"+c["default"](" ",n))}0===e&&(s=this.getIndent()+s),(this.format.compact||this.format.retainLines)&&"CommentLine"===t.type&&(s+="\n"),this._push(s),this.newline(this.whitespace.getNewlinesAfter(t))}},e.prototype.printComments=function(t){if(t&&t.length)for(var e=t,s=Array.isArray(e),i=0,e=s?e:n(e);;){var r;if(s){if(i>=e.length)break;r=e[i++]}else{if(i=e.next(),i.done)break;r=i.value}var a=r;this.printComment(a)}},e}(h["default"]);e["default"]=v;for(var g=[s(372),s(373),s(378),s(379),s(380),s(381),s(382),s(383),s(384),s(385)],x=0;x<g.length;x++){var A=g[x];a(v.prototype,A)}t.exports=e["default"]},function(t,e,s){t.exports={"default":s(276),__esModule:!0}},function(t,e,s){s(277),s(299),t.exports=s(302)},function(t,e,s){s(278);var i=s(281);i.NodeList=i.HTMLCollection=i.Array},function(t,e,s){"use strict";var i=s(279),r=s(280),n=s(281),a=s(282);t.exports=s(286)(Array,"Array",function(t,e){this._t=a(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,s=this._i++;return!t||s>=t.length?(this._t=void 0,r(1)):"keys"==e?r(0,s):"values"==e?r(0,t[s]):r(0,[s,t[s]])},"values"),n.Arguments=n.Array,i("keys"),i("values"),i("entries")},function(t,e){t.exports=function(){}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e){t.exports={}},function(t,e,s){var i=s(283),r=s(285);t.exports=function(t){return i(r(t))}},function(t,e,s){var i=s(284);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==i(t)?t.split(""):Object(t)}},function(t,e){var s={}.toString;t.exports=function(t){return s.call(t).slice(8,-1)}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,s){"use strict";var i=s(287),r=s(13),n=s(288),a=s(289),o=s(293),u=s(281),p=s(294),c=s(295),l=s(9).getProto,h=s(296)("iterator"),f=!([].keys&&"next"in[].keys()),d="@@iterator",y="keys",m="values",v=function(){return this};t.exports=function(t,e,s,g,x,A,b){p(s,e,g);var E,C,D=function(t){if(!f&&t in T)return T[t];switch(t){case y:return function(){return new s(this,t)};case m:return function(){return new s(this,t)}}return function(){return new s(this,t)}},S=e+" Iterator",F=x==m,w=!1,T=t.prototype,k=T[h]||T[d]||x&&T[x],P=k||D(x);if(k){var _=l(P.call(new t));c(_,S,!0),!i&&o(T,d)&&a(_,h,v),F&&k.name!==m&&(w=!0,P=function(){return k.call(this)})}if(i&&!b||!f&&!w&&T[h]||a(T,h,P),u[e]=P,u[S]=v,x)if(E={values:F?P:D(m),keys:A?P:D(y),entries:F?D("entries"):P},b)for(C in E)C in T||n(T,C,E[C]);else r(r.P+r.F*(f||w),e,E);return E}},function(t,e){t.exports=!0},function(t,e,s){t.exports=s(289)},function(t,e,s){var i=s(9),r=s(290);t.exports=s(291)?function(t,e,s){return i.setDesc(t,e,r(1,s))}:function(t,e,s){return t[e]=s,t}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,s){t.exports=!s(292)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(e){return!0}}},function(t,e){var s={}.hasOwnProperty;t.exports=function(t,e){return s.call(t,e)}},function(t,e,s){"use strict";var i=s(9),r=s(290),n=s(295),a={};s(289)(a,s(296)("iterator"),function(){return this}),t.exports=function(t,e,s){t.prototype=i.create(a,{next:r(1,s)}),n(t,e+" Iterator")}},function(t,e,s){var i=s(9).setDesc,r=s(293),n=s(296)("toStringTag");t.exports=function(t,e,s){t&&!r(t=s?t:t.prototype,n)&&i(t,n,{configurable:!0,value:e})}},function(t,e,s){var i=s(297)("wks"),r=s(298),n=s(14).Symbol;t.exports=function(t){return i[t]||(i[t]=n&&n[t]||(n||r)("Symbol."+t))}},function(t,e,s){var i=s(14),r="__core-js_shared__",n=i[r]||(i[r]={});t.exports=function(t){return n[t]||(n[t]={})}},function(t,e){var s=0,i=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++s+i).toString(36))}},function(t,e,s){"use strict";var i=s(300)(!0);s(286)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,s=this._i;return s>=e.length?{value:void 0,done:!0}:(t=i(e,s),this._i+=t.length,{value:t,done:!1})})},function(t,e,s){var i=s(301),r=s(285);t.exports=function(t){return function(e,s){var n,a,o=String(r(e)),u=i(s),p=o.length;return 0>u||u>=p?t?"":void 0:(n=o.charCodeAt(u),55296>n||n>56319||u+1===p||(a=o.charCodeAt(u+1))<56320||a>57343?t?o.charAt(u):n:t?o.slice(u,u+2):(n-55296<<10)+(a-56320)+65536)}}},function(t,e){var s=Math.ceil,i=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?i:s)(t)}},function(t,e,s){var i=s(20),r=s(303);t.exports=s(15).getIterator=function(t){var e=r(t);if("function"!=typeof e)throw TypeError(t+" is not iterable!");return i(e.call(t))}},function(t,e,s){var i=s(304),r=s(296)("iterator"),n=s(281);t.exports=s(15).getIteratorMethod=function(t){return void 0!=t?t[r]||t["@@iterator"]||n[i(t)]:void 0}},function(t,e,s){var i=s(284),r=s(296)("toStringTag"),n="Arguments"==i(function(){return arguments}());t.exports=function(t){var e,s,a;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(s=(e=Object(t))[r])?s:n?i(e):"Object"==(a=i(e))&&"function"==typeof e.callee?"Arguments":a}},function(t,e,s){t.exports={"default":s(306),__esModule:!0}},function(t,e,s){s(307),t.exports=s(15).Object.assign},function(t,e,s){var i=s(13);i(i.S+i.F,"Object",{assign:s(308)})},function(t,e,s){var i=s(9),r=s(309),n=s(283);t.exports=s(292)(function(){var t=Object.assign,e={},s={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach(function(t){s[t]=t}),7!=t({},e)[i]||Object.keys(t({},s)).join("")!=r})?function(t,e){for(var s=r(t),a=arguments,o=a.length,u=1,p=i.getKeys,c=i.getSymbols,l=i.isEnum;o>u;)for(var h,f=n(a[u++]),d=c?p(f).concat(c(f)):p(f),y=d.length,m=0;y>m;)l.call(f,h=d[m++])&&(s[h]=f[h]);return s}:Object.assign},function(t,e,s){var i=s(285);t.exports=function(t){return Object(i(t))}},function(t,e,s){"use strict";var i=s(21)["default"],r=s(22)["default"];e.__esModule=!0;var n=s(25),a=r(n),o=s(311),u=r(o),p=function(){function t(e,s){i(this,t),this.printedCommentStarts={},this.parenPushNewlineState=null,this.position=e,this._indent=s.indent.base,this.format=s,this.buf=""}return t.prototype.catchUp=function(t){if(t.loc&&this.format.retainLines&&this.buf)for(;this.position.line<t.loc.start.line;)this._push("\n")},t.prototype.get=function(){return u["default"](this.buf)},t.prototype.getIndent=function(){return this.format.compact||this.format.concise?"":a["default"](this.format.indent.style,this._indent)},t.prototype.indentSize=function(){return this.getIndent().length},t.prototype.indent=function(){this._indent++},t.prototype.dedent=function(){this._indent--},t.prototype.semicolon=function(){this.push(";")},t.prototype.ensureSemicolon=function(){this.isLast(";")||this.semicolon()},t.prototype.rightBrace=function(){this.newline(!0),this.format.minified&&!this._lastPrintedIsEmptyStatement&&this._removeLast(";"),this.push("}")},t.prototype.keyword=function(t){this.push(t),this.space()},t.prototype.space=function(t){(t||!this.format.compact)&&(t||this.buf&&!this.isLast(" ")&&!this.isLast("\n"))&&this.push(" ")},t.prototype.removeLast=function(t){return this.format.compact?void 0:this._removeLast(t)},t.prototype._removeLast=function(t){this._isLast(t)&&(this.buf=this.buf.substr(0,this.buf.length-1),this.position.unshift(t))},t.prototype.startTerminatorless=function(){return this.parenPushNewlineState={printed:!1}},t.prototype.endTerminatorless=function(t){t.printed&&(this.dedent(),this.newline(),this.push(")"))},t.prototype.newline=function(t,e){if(!this.format.retainLines&&!this.format.compact){if(this.format.concise)return void this.space();if(e=e||!1,"number"!=typeof t)"boolean"==typeof t&&(e=t),this._newline(e);else{if(t=Math.min(2,t),(this.endsWith("{\n")||this.endsWith(":\n"))&&t--,0>=t)return;for(;t>0;)this._newline(e),t--}}},t.prototype._newline=function(t){this.endsWith("\n\n")||(t&&this.isLast("\n")&&this.removeLast("\n"),this.removeLast(" "),this._removeSpacesAfterLastNewline(),this._push("\n"))},t.prototype._removeSpacesAfterLastNewline=function(){var t=this.buf.lastIndexOf("\n");if(-1!==t){for(var e=this.buf.length-1;e>t&&" "===this.buf[e];)e--;e===t&&(this.buf=this.buf.substring(0,e+1))}},t.prototype.push=function(t,e){if(!this.format.compact&&this._indent&&!e&&"\n"!==t){var s=this.getIndent();t=t.replace(/\n/g,"\n"+s),this.isLast("\n")&&this._push(s)}this._push(t)},t.prototype._push=function(t){var e=this.parenPushNewlineState;if(e)for(var s=0;s<t.length;s++){var i=t[s];if(" "!==i){this.parenPushNewlineState=null,("\n"===i||"/"===i)&&(this._push("("),this.indent(),e.printed=!0);break}}this.position.push(t),this.buf+=t},t.prototype.endsWith=function(t){var e=arguments.length<=1||void 0===arguments[1]?this.buf:arguments[1];return 1===t.length?e[e.length-1]===t:e.slice(-t.length)===t},t.prototype.isLast=function(t){return this.format.compact?!1:this._isLast(t)},t.prototype._isLast=function(t){var e=this.buf,s=e[e.length-1];return Array.isArray(t)?t.indexOf(s)>=0:t===s},t}();e["default"]=p,t.exports=e["default"]},function(t,e){"use strict";t.exports=function(t){for(var e=t.length;/[\s\uFEFF\u00A0]/.test(t[e-1]);)e--;return t.slice(0,e)}},function(t,e,s){"use strict";function i(t,e,s,i){if(t){for(var r=void 0,n=a(t),o=0;o<n.length;o++){var u=n[o];if(m.is(u,e)){var p=t[u];if(r=p(e,s,i),null!=r)break}}return r}}function r(t){return m.isCallExpression(t)?!0:m.isMemberExpression(t)?r(t.object)||!t.computed&&r(t.property):!1}var n=s(21)["default"],a=s(313)["default"],o=s(22)["default"],u=s(23)["default"];e.__esModule=!0;var p=s(317),c=o(p),l=s(371),h=u(l),f=s(320),d=o(f),y=s(41),m=u(y),v=function(){function t(e,s){n(this,t),this.parent=s,this.node=e}return t.isUserWhitespacable=function(t){return m.isUserWhitespacable(t)},t.needsWhitespace=function(e,s,r){if(!e)return 0;m.isExpressionStatement(e)&&(e=e.expression);var n=i(c["default"].nodes,e,s);if(!n){var a=i(c["default"].list,e,s);if(a)for(var o=0;o<a.length&&!(n=t.needsWhitespace(a[o],e,r));o++);}return n&&n[r]||0},t.needsWhitespaceBefore=function(e,s){return t.needsWhitespace(e,s,"before")},t.needsWhitespaceAfter=function(e,s){return t.needsWhitespace(e,s,"after")},t.needsParens=function(t,e,s){return e?m.isNewExpression(e)&&e.callee===t&&r(t)?!0:i(h,t,e,s):!1},t}();e["default"]=v,d["default"](v,function(t,e){v.prototype[e]=function(){var t=new Array(arguments.length+2);t[0]=this.node,t[1]=this.parent;for(var s=0;s<t.length;s++)t[s+2]=arguments[s];return v[e].apply(null,t)}}),t.exports=e["default"]},function(t,e,s){t.exports={"default":s(314),__esModule:!0}},function(t,e,s){s(315),t.exports=s(15).Object.keys},function(t,e,s){var i=s(309);s(316)("keys",function(t){return function(e){return t(i(e))}})},function(t,e,s){var i=s(13),r=s(15),n=s(292);t.exports=function(t,e){var s=(r.Object||{})[t]||Object[t],a={};a[t]=e(s),i(i.S+i.F*n(function(){s(1)}),"Object",a)}},function(t,e,s){"use strict";function i(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return y.isMemberExpression(t)?(i(t.object,e),t.computed&&i(t.property,e)):y.isBinary(t)||y.isAssignmentExpression(t)?(i(t.left,e),i(t.right,e)):y.isCallExpression(t)?(e.hasCall=!0,i(t.callee,e)):y.isFunction(t)?e.hasFunction=!0:y.isIdentifier(t)&&(e.hasHelper=e.hasHelper||r(t.callee)),e}function r(t){return y.isMemberExpression(t)?r(t.object)||r(t.property):y.isIdentifier(t)?"require"===t.name||"_"===t.name[0]:y.isCallExpression(t)?r(t.callee):y.isBinary(t)||y.isAssignmentExpression(t)?y.isIdentifier(t.left)&&r(t.left)||r(t.right):!1}function n(t){return y.isLiteral(t)||y.isObjectExpression(t)||y.isArrayExpression(t)||y.isIdentifier(t)||y.isMemberExpression(t)}var a=s(22)["default"],o=s(23)["default"],u=s(318),p=a(u),c=s(320),l=a(c),h=s(346),f=a(h),d=s(41),y=o(d);e.nodes={AssignmentExpression:function(t){var e=i(t.right);return e.hasCall&&e.hasHelper||e.hasFunction?{before:e.hasFunction,after:!0}:void 0},SwitchCase:function(t,e){return{before:t.consequent.length||e.cases[0]===t}},LogicalExpression:function(t){return y.isFunction(t.left)||y.isFunction(t.right)?{after:!0}:void 0},Literal:function(t){return"use strict"===t.value?{after:!0}:void 0},CallExpression:function(t){return y.isFunction(t.callee)||r(t)?{before:!0,after:!0}:void 0},VariableDeclaration:function(t){for(var e=0;e<t.declarations.length;e++){var s=t.declarations[e],a=r(s.id)&&!n(s.init);if(!a){var o=i(s.init);a=r(s.init)&&o.hasCall||o.hasFunction}if(a)return{before:!0,after:!0}}},IfStatement:function(t){return y.isBlockStatement(t.consequent)?{before:!0,after:!0}:void 0}},e.nodes.ObjectProperty=e.nodes.ObjectMethod=e.nodes.SpreadProperty=function(t,e){return e.properties[0]===t?{before:!0}:void 0},e.list={VariableDeclaration:function(t){return f["default"](t.declarations,"init")},ArrayExpression:function(t){return t.elements},ObjectExpression:function(t){return t.properties}},l["default"]({Function:!0,Class:!0,Loop:!0,LabeledStatement:!0,SwitchStatement:!0,TryStatement:!0},function(t,s){p["default"](t)&&(t={after:t,before:t}),l["default"]([s].concat(y.FLIPPED_ALIAS_KEYS[s]||[]),function(s){e.nodes[s]=function(){return t}})})},function(t,e,s){function i(t){return t===!0||t===!1||r(t)&&o.call(t)==n}var r=s(319),n="[object Boolean]",a=Object.prototype,o=a.toString;t.exports=i},function(t,e){function s(t){return!!t&&"object"==typeof t}t.exports=s},function(t,e,s){t.exports=s(321)},function(t,e,s){var i=s(322),r=s(323),n=s(343),a=n(i,r);t.exports=a},function(t,e){function s(t,e){for(var s=-1,i=t.length;++s<i&&e(t[s],s,t)!==!1;);return t}t.exports=s},function(t,e,s){var i=s(324),r=s(342),n=r(i);t.exports=n},function(t,e,s){function i(t,e){return r(t,e,n)}var r=s(325),n=s(329);t.exports=i},function(t,e,s){var i=s(326),r=i();t.exports=r},function(t,e,s){function i(t){return function(e,s,i){for(var n=r(e),a=i(e),o=a.length,u=t?o:-1;t?u--:++u<o;){var p=a[u];if(s(n[p],p,n)===!1)break}return e}}var r=s(327);t.exports=i},function(t,e,s){function i(t){return r(t)?t:Object(t)}var r=s(328);t.exports=i},function(t,e){function s(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}t.exports=s},function(t,e,s){var i=s(330),r=s(333),n=s(328),a=s(337),o=i(Object,"keys"),u=o?function(t){var e=null==t?void 0:t.constructor;return"function"==typeof e&&e.prototype===t||"function"!=typeof t&&r(t)?a(t):n(t)?o(t):[]}:a;t.exports=u},function(t,e,s){function i(t,e){var s=null==t?void 0:t[e];return r(s)?s:void 0}var r=s(331);t.exports=i},function(t,e,s){function i(t){return null==t?!1:r(t)?c.test(u.call(t)):n(t)&&a.test(t)}var r=s(332),n=s(319),a=/^\[object .+?Constructor\]$/,o=Object.prototype,u=Function.prototype.toString,p=o.hasOwnProperty,c=RegExp("^"+u.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=i},function(t,e,s){function i(t){return r(t)&&o.call(t)==n}var r=s(328),n="[object Function]",a=Object.prototype,o=a.toString;t.exports=i},function(t,e,s){function i(t){return null!=t&&n(r(t))}var r=s(334),n=s(336);t.exports=i},function(t,e,s){var i=s(335),r=i("length");t.exports=r},function(t,e){function s(t){return function(e){return null==e?void 0:e[t]}}t.exports=s},function(t,e){function s(t){return"number"==typeof t&&t>-1&&t%1==0&&i>=t}var i=9007199254740991;t.exports=s},function(t,e,s){function i(t){for(var e=u(t),s=e.length,i=s&&t.length,p=!!i&&o(i)&&(n(t)||r(t)),l=-1,h=[];++l<s;){var f=e[l];(p&&a(f,i)||c.call(t,f))&&h.push(f)}return h}var r=s(338),n=s(339),a=s(340),o=s(336),u=s(341),p=Object.prototype,c=p.hasOwnProperty;t.exports=i},function(t,e,s){function i(t){return n(t)&&r(t)&&o.call(t,"callee")&&!u.call(t,"callee")}var r=s(333),n=s(319),a=Object.prototype,o=a.hasOwnProperty,u=a.propertyIsEnumerable;t.exports=i},function(t,e,s){var i=s(330),r=s(336),n=s(319),a="[object Array]",o=Object.prototype,u=o.toString,p=i(Array,"isArray"),c=p||function(t){return n(t)&&r(t.length)&&u.call(t)==a};t.exports=c},function(t,e){function s(t,e){return t="number"==typeof t||i.test(t)?+t:-1,e=null==e?r:e,t>-1&&t%1==0&&e>t}var i=/^\d+$/,r=9007199254740991;t.exports=s},function(t,e,s){function i(t){if(null==t)return[];u(t)||(t=Object(t));var e=t.length;e=e&&o(e)&&(n(t)||r(t))&&e||0;for(var s=t.constructor,i=-1,p="function"==typeof s&&s.prototype===t,l=Array(e),h=e>0;++i<e;)l[i]=i+"";for(var f in t)h&&a(f,e)||"constructor"==f&&(p||!c.call(t,f))||l.push(f); return l}var r=s(338),n=s(339),a=s(340),o=s(336),u=s(328),p=Object.prototype,c=p.hasOwnProperty;t.exports=i},function(t,e,s){function i(t,e){return function(s,i){var o=s?r(s):0;if(!n(o))return t(s,i);for(var u=e?o:-1,p=a(s);(e?u--:++u<o)&&i(p[u],u,p)!==!1;);return s}}var r=s(334),n=s(336),a=s(327);t.exports=i},function(t,e,s){function i(t,e){return function(s,i,a){return"function"==typeof i&&void 0===a&&n(s)?t(s,i):e(s,r(i,a,3))}}var r=s(344),n=s(339);t.exports=i},function(t,e,s){function i(t,e,s){if("function"!=typeof t)return r;if(void 0===e)return t;switch(s){case 1:return function(s){return t.call(e,s)};case 3:return function(s,i,r){return t.call(e,s,i,r)};case 4:return function(s,i,r,n){return t.call(e,s,i,r,n)};case 5:return function(s,i,r,n,a){return t.call(e,s,i,r,n,a)}}return function(){return t.apply(e,arguments)}}var r=s(345);t.exports=i},function(t,e){function s(t){return t}t.exports=s},function(t,e,s){function i(t,e,s){var i=o(t)?r:a;return e=n(e,s,3),i(t,e)}var r=s(347),n=s(348),a=s(370),o=s(339);t.exports=i},function(t,e){function s(t,e){for(var s=-1,i=t.length,r=Array(i);++s<i;)r[s]=e(t[s],s,t);return r}t.exports=s},function(t,e,s){function i(t,e,s){var i=typeof t;return"function"==i?void 0===e?t:a(t,e,s):null==t?o:"object"==i?r(t):void 0===e?u(t):n(t,e)}var r=s(349),n=s(361),a=s(344),o=s(345),u=s(368);t.exports=i},function(t,e,s){function i(t){var e=n(t);if(1==e.length&&e[0][2]){var s=e[0][0],i=e[0][1];return function(t){return null==t?!1:t[s]===i&&(void 0!==i||s in a(t))}}return function(t){return r(t,e)}}var r=s(350),n=s(358),a=s(327);t.exports=i},function(t,e,s){function i(t,e,s){var i=e.length,a=i,o=!s;if(null==t)return!a;for(t=n(t);i--;){var u=e[i];if(o&&u[2]?u[1]!==t[u[0]]:!(u[0]in t))return!1}for(;++i<a;){u=e[i];var p=u[0],c=t[p],l=u[1];if(o&&u[2]){if(void 0===c&&!(p in t))return!1}else{var h=s?s(c,l,p):void 0;if(!(void 0===h?r(l,c,s,!0):h))return!1}}return!0}var r=s(351),n=s(327);t.exports=i},function(t,e,s){function i(t,e,s,o,u,p){return t===e?!0:null==t||null==e||!n(t)&&!a(e)?t!==t&&e!==e:r(t,e,i,s,o,u,p)}var r=s(352),n=s(328),a=s(319);t.exports=i},function(t,e,s){function i(t,e,s,i,h,y,m){var v=o(t),g=o(e),x=c,A=c;v||(x=d.call(t),x==p?x=l:x!=l&&(v=u(t))),g||(A=d.call(e),A==p?A=l:A!=l&&(g=u(e)));var b=x==l,E=A==l,C=x==A;if(C&&!v&&!b)return n(t,e,x);if(!h){var D=b&&f.call(t,"__wrapped__"),S=E&&f.call(e,"__wrapped__");if(D||S)return s(D?t.value():t,S?e.value():e,i,h,y,m)}if(!C)return!1;y||(y=[]),m||(m=[]);for(var F=y.length;F--;)if(y[F]==t)return m[F]==e;y.push(t),m.push(e);var w=(v?r:a)(t,e,s,i,h,y,m);return y.pop(),m.pop(),w}var r=s(353),n=s(355),a=s(356),o=s(339),u=s(357),p="[object Arguments]",c="[object Array]",l="[object Object]",h=Object.prototype,f=h.hasOwnProperty,d=h.toString;t.exports=i},function(t,e,s){function i(t,e,s,i,n,a,o){var u=-1,p=t.length,c=e.length;if(p!=c&&!(n&&c>p))return!1;for(;++u<p;){var l=t[u],h=e[u],f=i?i(n?h:l,n?l:h,u):void 0;if(void 0!==f){if(f)continue;return!1}if(n){if(!r(e,function(t){return l===t||s(l,t,i,n,a,o)}))return!1}else if(l!==h&&!s(l,h,i,n,a,o))return!1}return!0}var r=s(354);t.exports=i},function(t,e){function s(t,e){for(var s=-1,i=t.length;++s<i;)if(e(t[s],s,t))return!0;return!1}t.exports=s},function(t,e){function s(t,e,s){switch(s){case i:case r:return+t==+e;case n:return t.name==e.name&&t.message==e.message;case a:return t!=+t?e!=+e:t==+e;case o:case u:return t==e+""}return!1}var i="[object Boolean]",r="[object Date]",n="[object Error]",a="[object Number]",o="[object RegExp]",u="[object String]";t.exports=s},function(t,e,s){function i(t,e,s,i,n,o,u){var p=r(t),c=p.length,l=r(e),h=l.length;if(c!=h&&!n)return!1;for(var f=c;f--;){var d=p[f];if(!(n?d in e:a.call(e,d)))return!1}for(var y=n;++f<c;){d=p[f];var m=t[d],v=e[d],g=i?i(n?v:m,n?m:v,d):void 0;if(!(void 0===g?s(m,v,i,n,o,u):g))return!1;y||(y="constructor"==d)}if(!y){var x=t.constructor,A=e.constructor;if(x!=A&&"constructor"in t&&"constructor"in e&&!("function"==typeof x&&x instanceof x&&"function"==typeof A&&A instanceof A))return!1}return!0}var r=s(329),n=Object.prototype,a=n.hasOwnProperty;t.exports=i},function(t,e,s){function i(t){return n(t)&&r(t.length)&&!!k[_.call(t)]}var r=s(336),n=s(319),a="[object Arguments]",o="[object Array]",u="[object Boolean]",p="[object Date]",c="[object Error]",l="[object Function]",h="[object Map]",f="[object Number]",d="[object Object]",y="[object RegExp]",m="[object Set]",v="[object String]",g="[object WeakMap]",x="[object ArrayBuffer]",A="[object Float32Array]",b="[object Float64Array]",E="[object Int8Array]",C="[object Int16Array]",D="[object Int32Array]",S="[object Uint8Array]",F="[object Uint8ClampedArray]",w="[object Uint16Array]",T="[object Uint32Array]",k={};k[A]=k[b]=k[E]=k[C]=k[D]=k[S]=k[F]=k[w]=k[T]=!0,k[a]=k[o]=k[x]=k[u]=k[p]=k[c]=k[l]=k[h]=k[f]=k[d]=k[y]=k[m]=k[v]=k[g]=!1;var P=Object.prototype,_=P.toString;t.exports=i},function(t,e,s){function i(t){for(var e=n(t),s=e.length;s--;)e[s][2]=r(e[s][1]);return e}var r=s(359),n=s(360);t.exports=i},function(t,e,s){function i(t){return t===t&&!r(t)}var r=s(328);t.exports=i},function(t,e,s){function i(t){t=n(t);for(var e=-1,s=r(t),i=s.length,a=Array(i);++e<i;){var o=s[e];a[e]=[o,t[o]]}return a}var r=s(329),n=s(327);t.exports=i},function(t,e,s){function i(t,e){var s=o(t),i=u(t)&&p(e),f=t+"";return t=h(t),function(o){if(null==o)return!1;var u=f;if(o=l(o),(s||!i)&&!(u in o)){if(o=1==t.length?o:r(o,a(t,0,-1)),null==o)return!1;u=c(t),o=l(o)}return o[u]===e?void 0!==e||u in o:n(e,o[u],void 0,!0)}}var r=s(362),n=s(351),a=s(363),o=s(339),u=s(364),p=s(359),c=s(365),l=s(327),h=s(366);t.exports=i},function(t,e,s){function i(t,e,s){if(null!=t){void 0!==s&&s in r(t)&&(e=[s]);for(var i=0,n=e.length;null!=t&&n>i;)t=t[e[i++]];return i&&i==n?t:void 0}}var r=s(327);t.exports=i},function(t,e){function s(t,e,s){var i=-1,r=t.length;e=null==e?0:+e||0,0>e&&(e=-e>r?0:r+e),s=void 0===s||s>r?r:+s||0,0>s&&(s+=r),r=e>s?0:s-e>>>0,e>>>=0;for(var n=Array(r);++i<r;)n[i]=t[i+e];return n}t.exports=s},function(t,e,s){function i(t,e){var s=typeof t;if("string"==s&&o.test(t)||"number"==s)return!0;if(r(t))return!1;var i=!a.test(t);return i||null!=e&&t in n(e)}var r=s(339),n=s(327),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,o=/^\w*$/;t.exports=i},function(t,e){function s(t){var e=t?t.length:0;return e?t[e-1]:void 0}t.exports=s},function(t,e,s){function i(t){if(n(t))return t;var e=[];return r(t).replace(a,function(t,s,i,r){e.push(i?r.replace(o,"$1"):s||t)}),e}var r=s(367),n=s(339),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,o=/\\(\\)?/g;t.exports=i},function(t,e){function s(t){return null==t?"":t+""}t.exports=s},function(t,e,s){function i(t){return a(t)?r(t):n(t)}var r=s(335),n=s(369),a=s(364);t.exports=i},function(t,e,s){function i(t){var e=t+"";return t=n(t),function(s){return r(s,t,e)}}var r=s(362),n=s(366);t.exports=i},function(t,e,s){function i(t,e){var s=-1,i=n(t)?Array(t.length):[];return r(t,function(t,r,n){i[++s]=e(t,r,n)}),i}var r=s(323),n=s(333);t.exports=i},function(t,e,s){"use strict";function i(t,e){return x.isArrayTypeAnnotation(e)}function r(t,e){return x.isMemberExpression(e)&&e.object===t?!0:!1}function n(t,e,s){return x.isExpressionStatement(e)?!0:m(s)}function a(t,e){if((x.isCallExpression(e)||x.isNewExpression(e))&&e.callee===t)return!0;if(x.isUnaryLike(e))return!0;if(x.isMemberExpression(e)&&e.object===t)return!0;if(x.isBinary(e)){var s=e.operator,i=A[s],r=t.operator,n=A[r];if(i>n)return!0;if(i===n&&e.right===t&&!x.isLogicalExpression(e))return!0}return!1}function o(t,e){if("in"===t.operator){if(x.isVariableDeclarator(e))return!0;if(x.isFor(e))return!0}return!1}function u(t,e){return x.isForStatement(e)?!1:x.isExpressionStatement(e)&&e.expression===t?!1:x.isReturnStatement(e)?!1:x.isThrowStatement(e)?!1:x.isSwitchStatement(e)&&e.discriminant===t?!1:x.isWhileStatement(e)&&e.test===t?!1:x.isIfStatement(e)&&e.test===t?!1:x.isForInStatement(e)&&e.right===t?!1:!0}function p(t,e){return x.isBinary(e)||x.isUnaryLike(e)||x.isCallExpression(e)||x.isMemberExpression(e)||x.isNewExpression(e)}function c(t,e){return x.isExpressionStatement(e)?!0:x.isExportDeclaration(e)?!0:!1}function l(t,e){return x.isMemberExpression(e,{object:t})?!0:x.isCallExpression(e,{callee:t})||x.isNewExpression(e,{callee:t})?!0:!1}function h(t,e,s){return x.isExpressionStatement(e)?!0:x.isExportDeclaration(e)?!0:m(s)}function f(t,e){return x.isExportDeclaration(e)?!0:x.isBinaryExpression(e)||x.isLogicalExpression(e)?!0:l(t,e)}function d(t,e){return x.isUnaryLike(e)?!0:x.isBinary(e)?!0:x.isConditionalExpression(e,{test:t})?!0:l(t,e)}function y(t){return x.isObjectPattern(t.left)?!0:d.apply(void 0,arguments)}function m(t){var e=t.length-1,s=t[e];e--;for(var i=t[e];e>0;){if(x.isExpressionStatement(i,{expression:s}))return!0;if(!(x.isCallExpression(i,{callee:s})||x.isSequenceExpression(i)&&i.expressions[0]===s||x.isMemberExpression(i,{object:s})||x.isConditional(i,{test:s})||x.isBinary(i,{left:s})||x.isAssignmentExpression(i,{left:s})))return!1;s=i,e--,i=t[e]}return!1}var v=s(23)["default"];e.__esModule=!0,e.NullableTypeAnnotation=i,e.UpdateExpression=r,e.ObjectExpression=n,e.Binary=a,e.BinaryExpression=o,e.SequenceExpression=u,e.YieldExpression=p,e.ClassExpression=c,e.UnaryLike=l,e.FunctionExpression=h,e.ArrowFunctionExpression=f,e.ConditionalExpression=d,e.AssignmentExpression=y;var g=s(41),x=v(g),A={"||":0,"&&":1,"|":2,"^":3,"&":4,"==":5,"===":5,"!=":5,"!==":5,"<":6,">":6,"<=":6,">=":6,"in":6,"instanceof":6,">>":7,"<<":7,">>>":7,"+":8,"-":8,"*":9,"/":9,"%":9,"**":10};e.FunctionTypeAnnotation=i,e.AwaitExpression=p},function(t,e){"use strict";function s(t){this.print(t.tag,t),this.print(t.quasi,t)}function i(t){this._push(t.value.raw)}function r(t){this.push("`");for(var e=t.quasis,s=0;s<e.length;s++)this.print(e[s],t),s+1<e.length&&(this._push("${ "),this.print(t.expressions[s],t),this.push(" }"));this._push("`")}e.__esModule=!0,e.TaggedTemplateExpression=s,e.TemplateElement=i,e.TemplateLiteral=r},function(t,e,s){"use strict";function i(t){var e=/[a-z]$/.test(t.operator),s=t.argument;(P.isUpdateExpression(s)||P.isUnaryExpression(s))&&(e=!0),P.isUnaryExpression(s)&&"!"===s.operator&&(e=!1),this.push(t.operator),e&&this.push(" "),this.print(t.argument,t)}function r(t){this.push("do"),this.space(),this.print(t.body,t)}function n(t){this.push("("),this.print(t.expression,t),this.push(")")}function a(t){t.prefix?(this.push(t.operator),this.print(t.argument,t)):(this.print(t.argument,t),this.push(t.operator))}function o(t){this.print(t.test,t),this.space(),this.push("?"),this.space(),this.print(t.consequent,t),this.space(),this.push(":"),this.space(),this.print(t.alternate,t)}function u(t,e){this.push("new "),this.print(t.callee,t),(0!==t.arguments.length||!this.format.minified||P.isCallExpression(e,{callee:t})||P.isMemberExpression(e)||P.isNewExpression(e))&&(this.push("("),this.printList(t.arguments,t),this.push(")"))}function p(t){this.printList(t.expressions,t)}function c(){this.push("this")}function l(){this.push("super")}function h(t){this.push("@"),this.print(t.expression,t),this.newline()}function f(t){this.print(t.callee,t),t.loc&&this.printAuxAfterComment(),this.push("(");var e=t._prettyCall&&!this.format.retainLines&&!this.format.compact,s=void 0;e&&(s=",\n",this.newline(),this.indent()),this.printList(t.arguments,t,{separator:s}),e&&(this.newline(),this.dedent()),this.push(")")}function d(t){return function(e){if(this.push(t),e.delegate&&this.push("*"),e.argument){this.push(" ");var s=this.startTerminatorless();this.print(e.argument,e),this.endTerminatorless(s)}}}function y(){this._lastPrintedIsEmptyStatement=!0,this.semicolon()}function m(t){this.print(t.expression,t),this.semicolon()}function v(t){this.print(t.left,t),this.space(),this.push("="),this.space(),this.print(t.right,t)}function g(t,e){var s=this._inForStatementInit&&"in"===t.operator&&!B["default"].needsParens(t,e);s&&this.push("("),this.print(t.left,t);var i=!this.format.compact||"in"===t.operator||"instanceof"===t.operator;if(i&&this.push(" "),this.push(t.operator),!i&&(i="<"===t.operator&&P.isUnaryExpression(t.right,{prefix:!0,operator:"!"})&&P.isUnaryExpression(t.right.argument,{prefix:!0,operator:"--"}),!i)){var r=E(t.right);i=P.isUnaryExpression(r,{prefix:!0,operator:t.operator})||P.isUpdateExpression(r,{prefix:!0,operator:t.operator+t.operator})}i&&this.push(" "),this.print(t.right,t),s&&this.push(")")}function x(t){this.print(t.object,t),this.push("::"),this.print(t.callee,t)}function A(t){if(this.print(t.object,t),!t.computed&&P.isMemberExpression(t.property))throw new TypeError("Got a MemberExpression for MemberExpression property");var e=t.computed;if(P.isLiteral(t.property)&&T["default"](t.property.value)&&(e=!0),e)this.push("["),this.print(t.property,t),this.push("]");else{if(P.isNumericLiteral(t.object)){var s=this.getPossibleRaw(t.object)||t.object.value;!F["default"](+s)||N.test(s)||L.test(s)||this.endsWith(".")||this.push(".")}this.push("."),this.print(t.property,t)}}function b(t){this.print(t.meta,t),this.push("."),this.print(t.property,t)}function E(t){return P.isBinaryExpression(t)?E(t.left):t}var C=s(22)["default"],D=s(23)["default"];e.__esModule=!0,e.UnaryExpression=i,e.DoExpression=r,e.ParenthesizedExpression=n,e.UpdateExpression=a,e.ConditionalExpression=o,e.NewExpression=u,e.SequenceExpression=p,e.ThisExpression=c,e.Super=l,e.Decorator=h,e.CallExpression=f,e.EmptyStatement=y,e.ExpressionStatement=m,e.AssignmentPattern=v,e.AssignmentExpression=g,e.BindExpression=x,e.MemberExpression=A,e.MetaProperty=b;var S=s(374),F=C(S),w=s(377),T=C(w),k=s(41),P=D(k),_=s(312),B=C(_),N=/e/i,L=/\.0+$/,I=d("yield");e.YieldExpression=I;var O=d("await");e.AwaitExpression=O,e.BinaryExpression=g,e.LogicalExpression=g},function(t,e,s){var i=s(375);t.exports=Number.isInteger||function(t){return"number"==typeof t&&i(t)&&Math.floor(t)===t}},function(t,e,s){"use strict";var i=s(376);t.exports=Number.isFinite||function(t){return!("number"!=typeof t||i(t)||t===1/0||t===-(1/0))}},function(t,e){"use strict";t.exports=Number.isNaN||function(t){return t!==t}},function(t,e,s){function i(t){return"number"==typeof t||r(t)&&o.call(t)==n}var r=s(319),n="[object Number]",a=Object.prototype,o=a.toString;t.exports=i},function(t,e,s){"use strict";function i(t){this.keyword("with"),this.push("("),this.print(t.object,t),this.push(")"),this.printBlock(t)}function r(t){this.keyword("if"),this.push("("),this.print(t.test,t),this.push(")"),this.space();var e=t.alternate&&D.isIfStatement(n(t.consequent));e&&(this.push("{"),this.newline(),this.indent()),this.printAndIndentOnComments(t.consequent,t),e&&(this.dedent(),this.newline(),this.push("}")),t.alternate&&(this.isLast("}")&&this.space(),this.push("else "),this.printAndIndentOnComments(t.alternate,t))}function n(t){return D.isStatement(t.body)?n(t.body):t}function a(t){this.keyword("for"),this.push("("),this._inForStatementInit=!0,this.print(t.init,t),this._inForStatementInit=!1,this.push(";"),t.test&&(this.space(),this.print(t.test,t)),this.push(";"),t.update&&(this.space(),this.print(t.update,t)),this.push(")"),this.printBlock(t)}function o(t){this.keyword("while"),this.push("("),this.print(t.test,t),this.push(")"),this.printBlock(t)}function u(t){this.push("do "),this.print(t.body,t),this.space(),this.keyword("while"),this.push("("),this.print(t.test,t),this.push(");")}function p(t){var e=arguments.length<=1||void 0===arguments[1]?"label":arguments[1];return function(s){this.push(t);var i=s[e];if(i){this.format.minified&&(D.isUnaryExpression(i,{prefix:!0})||D.isUpdateExpression(i,{prefix:!0}))&&S.indexOf(i.operator)>-1||this.push(" ");var r=this.startTerminatorless();this.print(i,s),this.endTerminatorless(r)}this.semicolon()}}function c(t){this.print(t.label,t),this.push(": "),this.print(t.body,t)}function l(t){this.keyword("try"),this.print(t.block,t),this.space(),t.handlers?this.print(t.handlers[0],t):this.print(t.handler,t),t.finalizer&&(this.space(),this.push("finally "),this.print(t.finalizer,t))}function h(t){this.keyword("catch"),this.push("("),this.print(t.param,t),this.push(")"),this.space(),this.print(t.body,t)}function f(t){this.keyword("switch"),this.push("("),this.print(t.discriminant,t),this.push(")"),this.space(),this.push("{"),this.printSequence(t.cases,t,{indent:!0,addNewlines:function(e,s){return e||t.cases[t.cases.length-1]!==s?void 0:-1}}),this.push("}")}function d(t){t.test?(this.push("case "),this.print(t.test,t),this.push(":")):this.push("default:"),t.consequent.length&&(this.newline(),this.printSequence(t.consequent,t,{indent:!0}))}function y(){this.push("debugger;")}function m(t,e){this.push(t.kind+" ");var s=!1;if(!D.isFor(e))for(var i=t.declarations,r=Array.isArray(i),n=0,i=r?i:g(i);;){var a;if(r){if(n>=i.length)break;a=i[n++]}else{if(n=i.next(),n.done)break;a=n.value}var o=a;o.init&&(s=!0)}var u=void 0;this.format.compact||this.format.concise||!s||this.format.retainLines||(u=",\n"+E["default"](" ",t.kind.length+1)),this.printList(t.declarations,t,{separator:u}),(!D.isFor(e)||e.left!==t&&e.init!==t)&&this.semicolon()}function v(t){this.print(t.id,t),this.print(t.id.typeAnnotation,t),t.init&&(this.space(),this.push("="),this.space(),this.print(t.init,t))}var g=s(275)["default"],x=s(22)["default"],A=s(23)["default"];e.__esModule=!0,e.WithStatement=i,e.IfStatement=r,e.ForStatement=a,e.WhileStatement=o,e.DoWhileStatement=u,e.LabeledStatement=c,e.TryStatement=l,e.CatchClause=h,e.SwitchStatement=f,e.SwitchCase=d,e.DebuggerStatement=y,e.VariableDeclaration=m,e.VariableDeclarator=v;var b=s(25),E=x(b),C=s(41),D=A(C),S=D.UPDATE_OPERATORS.concat(D.NUMBER_UNARY_OPERATORS).concat(["!"]),F=function(t){return function(e){this.keyword("for"),this.push("("),this.print(e.left,e),this.push(" "+t+" "),this.print(e.right,e),this.push(")"),this.printBlock(e)}},w=F("in");e.ForInStatement=w;var T=F("of");e.ForOfStatement=T;var k=p("continue");e.ContinueStatement=k;var P=p("return","argument");e.ReturnStatement=P;var _=p("break");e.BreakStatement=_;var B=p("throw","argument");e.ThrowStatement=B},function(t,e){"use strict";function s(t){this.printJoin(t.decorators,t,{separator:""}),this.push("class"),t.id&&(this.push(" "),this.print(t.id,t)),this.print(t.typeParameters,t),t.superClass&&(this.push(" extends "),this.print(t.superClass,t),this.print(t.superTypeParameters,t)),t["implements"]&&(this.push(" implements "),this.printJoin(t["implements"],t,{separator:", "})),this.space(),this.print(t.body,t)}function i(t){this.push("{"),this.printInnerComments(t),0===t.body.length?this.push("}"):(this.newline(),this.indent(),this.printSequence(t.body,t),this.dedent(),this.rightBrace())}function r(t){this.printJoin(t.decorators,t,{separator:""}),t["static"]&&this.push("static "),this.print(t.key,t),this.print(t.typeAnnotation,t),t.value&&(this.space(),this.push("="),this.space(),this.print(t.value,t)),this.semicolon()}function n(t){this.printJoin(t.decorators,t,{separator:""}),t["static"]&&this.push("static "),"constructorCall"===t.kind&&this.push("call "),this._method(t)}e.__esModule=!0,e.ClassDeclaration=s,e.ClassBody=i,e.ClassProperty=r,e.ClassMethod=n,e.ClassExpression=s},function(t,e,s){"use strict";function i(t){var e=this;this.print(t.typeParameters,t),this.push("("),this.printList(t.params,t,{iterator:function(t){t.optional&&e.push("?"),e.print(t.typeAnnotation,t)}}),this.push(")"),t.returnType&&this.print(t.returnType,t)}function r(t){var e=t.kind,s=t.key;("method"===e||"init"===e)&&t.generator&&this.push("*"),("get"===e||"set"===e)&&this.push(e+" "),t.async&&this.push("async "),t.computed?(this.push("["),this.print(s,t),this.push("]")):this.print(s,t),this._params(t),this.space(),this.print(t.body,t)}function n(t){t.async&&this.push("async "),this.push("function"),t.generator&&this.push("*"),t.id?(this.push(" "),this.print(t.id,t)):this.space(),this._params(t),this.space(),this.print(t.body,t)}function a(t){t.async&&this.push("async "),1===t.params.length&&p.isIdentifier(t.params[0])?this.print(t.params[0],t):this._params(t),this.push(" => ");var e=p.isObjectExpression(t.body);e&&this.push("("),this.print(t.body,t),e&&this.push(")")}var o=s(23)["default"];e.__esModule=!0,e._params=i,e._method=r,e.FunctionExpression=n,e.ArrowFunctionExpression=a;var u=s(41),p=o(u);e.FunctionDeclaration=n},function(t,e,s){"use strict";function i(t){this.print(t.imported,t),t.local&&t.local.name!==t.imported.name&&(this.push(" as "),this.print(t.local,t))}function r(t){this.print(t.local,t)}function n(t){this.print(t.exported,t)}function a(t){this.print(t.local,t),t.exported&&t.local.name!==t.exported.name&&(this.push(" as "),this.print(t.exported,t))}function o(t){this.push("* as "),this.print(t.exported,t)}function u(t){this.push("export *"),t.exported&&(this.push(" as "),this.print(t.exported,t)),this.push(" from "),this.print(t.source,t),this.semicolon()}function p(){this.push("export "),l.apply(this,arguments)}function c(){this.push("export default "),l.apply(this,arguments)}function l(t){if(t.declaration){var e=t.declaration;if(this.print(e,t),m.isStatement(e)||m.isFunction(e)||m.isClass(e))return}else{"type"===t.exportKind&&this.push("type ");for(var s=t.specifiers.slice(0),i=!1;;){var r=s[0];if(!m.isExportDefaultSpecifier(r)&&!m.isExportNamespaceSpecifier(r))break;i=!0,this.print(s.shift(),t),s.length&&this.push(", ")}(s.length||!s.length&&!i)&&(this.push("{"),s.length&&(this.space(),this.printJoin(s,t,{separator:", "}),this.space()),this.push("}")),t.source&&(this.push(" from "),this.print(t.source,t))}this.ensureSemicolon()}function h(t){this.push("import "),("type"===t.importKind||"typeof"===t.importKind)&&this.push(t.importKind+" ");var e=t.specifiers.slice(0);if(e&&e.length){for(;;){var s=e[0];if(!m.isImportDefaultSpecifier(s)&&!m.isImportNamespaceSpecifier(s))break;this.print(e.shift(),t),e.length&&this.push(", ")}e.length&&(this.push("{"),this.space(),this.printJoin(e,t,{separator:", "}),this.space(),this.push("}")),this.push(" from ")}this.print(t.source,t),this.semicolon()}function f(t){this.push("* as "),this.print(t.local,t)}var d=s(23)["default"];e.__esModule=!0,e.ImportSpecifier=i,e.ImportDefaultSpecifier=r,e.ExportDefaultSpecifier=n,e.ExportSpecifier=a,e.ExportNamespaceSpecifier=o,e.ExportAllDeclaration=u,e.ExportNamedDeclaration=p,e.ExportDefaultDeclaration=c,e.ImportDeclaration=h,e.ImportNamespaceSpecifier=f;var y=s(41),m=d(y)},function(t,e,s){"use strict";function i(t){this.push(t.name)}function r(t){this.push("..."),this.print(t.argument,t)}function n(t){var e=t.properties;this.push("{"),this.printInnerComments(t),e.length&&(this.space(),this.printList(e,t,{indent:!0}),this.space()),this.push("}")}function a(t){this.printJoin(t.decorators,t,{separator:""}),this._method(t)}function o(t){if(this.printJoin(t.decorators,t,{separator:""}),t.computed)this.push("["),this.print(t.key,t),this.push("]");else{if(v.isAssignmentPattern(t.value)&&v.isIdentifier(t.key)&&t.key.name===t.value.left.name)return void this.print(t.value,t);if(this.print(t.key,t),t.shorthand&&v.isIdentifier(t.key)&&v.isIdentifier(t.value)&&t.key.name===t.value.name)return}this.push(":"),this.space(),this.print(t.value,t)}function u(t){var e=t.elements,s=e.length;this.push("["),this.printInnerComments(t);for(var i=0;i<e.length;i++){var r=e[i];r?(i>0&&this.space(),this.print(r,t),s-1>i&&this.push(",")):this.push(",")}this.push("]")}function p(t){this.push("/"+t.pattern+"/"+t.flags)}function c(t){this.push(t.value?"true":"false")}function l(){this.push("null")}function h(t){this.push(t.value+"")}function f(t,e){this.push(this._stringLiteral(t.value,e))}function d(t,e){return t=JSON.stringify(t),t=t.replace(/[\u000A\u000D\u2028\u2029]/g,function(t){return"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)}),"single"!==this.format.quotes||v.isJSX(e)||(t=t.slice(1,-1),t=t.replace(/\\"/g,'"'),t=t.replace(/'/g,"\\'"),t="'"+t+"'"),t}var y=s(23)["default"];e.__esModule=!0,e.Identifier=i,e.RestElement=r,e.ObjectExpression=n,e.ObjectMethod=a,e.ObjectProperty=o,e.ArrayExpression=u,e.RegExpLiteral=p,e.BooleanLiteral=c,e.NullLiteral=l,e.NumericLiteral=h,e.StringLiteral=f,e._stringLiteral=d;var m=s(41),v=y(m);e.SpreadElement=r,e.SpreadProperty=r,e.RestProperty=r,e.ObjectPattern=n,e.ArrayPattern=u},function(t,e,s){"use strict";function i(){this.push("any")}function r(t){this.print(t.elementType,t),this.push("["),this.push("]")}function n(){this.push("bool")}function a(t){this.push(t.value?"true":"false")}function o(){this.push("null")}function u(t){this.push("declare class "),this._interfaceish(t)}function p(t){this.push("declare function "),this.print(t.id,t),this.print(t.id.typeAnnotation.typeAnnotation,t),this.semicolon()}function c(t){this.push("declare "),this.InterfaceDeclaration(t)}function l(t){this.push("declare module "),this.print(t.id,t),this.space(),this.print(t.body,t)}function h(t){this.push("declare "),this.TypeAlias(t)}function f(t){this.push("declare var "),this.print(t.id,t),this.print(t.id.typeAnnotation,t),this.semicolon()}function d(){this.push("*")}function y(t,e){this.print(t.typeParameters,t),this.push("("),this.printList(t.params,t),t.rest&&(t.params.length&&(this.push(","),this.space()),this.push("..."),this.print(t.rest,t)),this.push(")"),"ObjectTypeProperty"===e.type||"ObjectTypeCallProperty"===e.type||"DeclareFunction"===e.type?this.push(":"):(this.space(),this.push("=>")),this.space(),this.print(t.returnType,t)}function m(t){this.print(t.name,t),t.optional&&this.push("?"),this.push(":"),this.space(),this.print(t.typeAnnotation,t)}function v(t){this.print(t.id,t),this.print(t.typeParameters,t)}function g(t){this.print(t.id,t),this.print(t.typeParameters,t),t["extends"].length&&(this.push(" extends "),this.printJoin(t["extends"],t,{separator:", "})),t.mixins&&t.mixins.length&&(this.push(" mixins "),this.printJoin(t.mixins,t,{separator:", "})),this.space(),this.print(t.body,t)}function x(t){this.push("interface "),this._interfaceish(t)}function A(t){this.printJoin(t.types,t,{separator:" & "})}function b(){this.push("mixed")}function E(t){this.push("?"),this.print(t.typeAnnotation,t)}function C(){this.push("number")}function D(t){this.push(this._stringLiteral(t.value))}function S(){this.push("string")}function F(){this.push("this")}function w(t){this.push("["),this.printJoin(t.types,t,{separator:", "}),this.push("]")}function T(t){this.push("typeof "),this.print(t.argument,t)}function k(t){this.push("type "),this.print(t.id,t),this.print(t.typeParameters,t),this.space(),this.push("="),this.space(),this.print(t.right,t),this.semicolon()}function P(t){this.push(":"),this.space(),t.optional&&this.push("?"),this.print(t.typeAnnotation,t)}function _(t){var e=this;this.push("<"),this.printJoin(t.params,t,{separator:", ",iterator:function(t){e.print(t.typeAnnotation,t)}}),this.push(">")}function B(t){var e=this;this.push("{");var s=t.properties.concat(t.callProperties,t.indexers);s.length&&(this.space(),this.printJoin(s,t,{separator:!1,indent:!0,iterator:function(){1!==s.length&&(e.semicolon(),e.space())}}),this.space()),this.push("}")}function N(t){t["static"]&&this.push("static "),this.print(t.value,t)}function L(t){t["static"]&&this.push("static "),this.push("["),this.print(t.id,t),this.push(":"),this.space(),this.print(t.key,t),this.push("]"),this.push(":"),this.space(),this.print(t.value,t)}function I(t){t["static"]&&this.push("static "),this.print(t.key,t),t.optional&&this.push("?"),G.isFunctionTypeAnnotation(t.value)||(this.push(":"),this.space()),this.print(t.value,t)}function O(t){this.print(t.qualification,t),this.push("."),this.print(t.id,t)}function M(t){this.printJoin(t.types,t,{separator:" | "})}function j(t){this.push("("),this.print(t.expression,t),this.print(t.typeAnnotation,t),this.push(")")}function R(){this.push("void")}var V=s(23)["default"];e.__esModule=!0,e.AnyTypeAnnotation=i,e.ArrayTypeAnnotation=r,e.BooleanTypeAnnotation=n,e.BooleanLiteralTypeAnnotation=a,e.NullLiteralTypeAnnotation=o,e.DeclareClass=u,e.DeclareFunction=p,e.DeclareInterface=c,e.DeclareModule=l,e.DeclareTypeAlias=h,e.DeclareVariable=f,e.ExistentialTypeParam=d,e.FunctionTypeAnnotation=y,e.FunctionTypeParam=m,e.InterfaceExtends=v,e._interfaceish=g,e.InterfaceDeclaration=x,e.IntersectionTypeAnnotation=A,e.MixedTypeAnnotation=b,e.NullableTypeAnnotation=E,e.NumberTypeAnnotation=C,e.StringLiteralTypeAnnotation=D,e.StringTypeAnnotation=S,e.ThisTypeAnnotation=F,e.TupleTypeAnnotation=w,e.TypeofTypeAnnotation=T,e.TypeAlias=k,e.TypeAnnotation=P,e.TypeParameterInstantiation=_,e.ObjectTypeAnnotation=B,e.ObjectTypeCallProperty=N,e.ObjectTypeIndexer=L,e.ObjectTypeProperty=I,e.QualifiedTypeIdentifier=O,e.UnionTypeAnnotation=M,e.TypeCastExpression=j,e.VoidTypeAnnotation=R;var $=s(41),G=V($);e.ClassImplements=v,e.GenericTypeAnnotation=v;var q=s(382);e.NumericLiteralTypeAnnotation=q.NumericLiteral,e.TypeParameterDeclaration=_},function(t,e){"use strict";function s(t){this.print(t.program,t)}function i(t){this.printInnerComments(t,!1),this.printSequence(t.directives,t),t.directives&&t.directives.length&&this.newline(),this.printSequence(t.body,t)}function r(t){this.push("{"),this.printInnerComments(t),t.body.length?(this.newline(),this.printSequence(t.directives,t,{indent:!0}),t.directives&&t.directives.length&&this.newline(),this.printSequence(t.body,t,{indent:!0}),this.format.retainLines||this.removeLast("\n"),this.rightBrace()):this.push("}")}function n(){}function a(t){this.print(t.value,t),this.semicolon()}function o(t){this.push(this._stringLiteral(t.value))}e.__esModule=!0,e.File=s,e.Program=i,e.BlockStatement=r,e.Noop=n,e.Directive=a,e.DirectiveLiteral=o},function(t,e,s){"use strict";function i(t){this.print(t.name,t),t.value&&(this.push("="),this.print(t.value,t))}function r(t){this.push(t.name)}function n(t){this.print(t.namespace,t),this.push(":"),this.print(t.name,t)}function a(t){this.print(t.object,t),this.push("."),this.print(t.property,t)}function o(t){this.push("{..."),this.print(t.argument,t),this.push("}")}function u(t){this.push("{"),this.print(t.expression,t),this.push("}")}function p(t){this.push(t.value,!0)}function c(t){var e=t.openingElement;if(this.print(e,t),!e.selfClosing){this.indent();for(var s=t.children,i=Array.isArray(s),r=0,s=i?s:d(s);;){var n;if(i){if(r>=s.length)break;n=s[r++]}else{if(r=s.next(),r.done)break;n=r.value}var a=n;this.print(a,t)}this.dedent(),this.print(t.closingElement,t)}}function l(t){this.push("<"),this.print(t.name,t),t.attributes.length>0&&(this.push(" "),this.printJoin(t.attributes,t,{separator:" "})),this.push(t.selfClosing?" />":">")}function h(t){this.push("</"),this.print(t.name,t),this.push(">")}function f(){}var d=s(275)["default"];e.__esModule=!0,e.JSXAttribute=i,e.JSXIdentifier=r,e.JSXNamespacedName=n,e.JSXMemberExpression=a,e.JSXSpreadAttribute=o,e.JSXExpressionContainer=u,e.JSXText=p,e.JSXElement=c,e.JSXOpeningElement=l,e.JSXClosingElement=h,e.JSXEmptyExpression=f},function(t,e){t.exports=function s(t,e){var i;t=t||{};for(i in e)"object"==typeof e[i]?t[i]=s(t[i],e[i]):t[i]=e[i];return t}},function(t,e){var s=0;t.exports=function(){return"_"+ ++s},t.exports.resetIDs=function(){s=0}},function(t,e,s){var i,r,n,a,o,u=s(4),p=s(389),c=s(387),l=s(41),h=s(390),f=s(3).isIgnored,d=function(t,e){var s,i;if(t&&"CallExpression"===t.type&&t.callee&&"MemberExpression"===t.callee.type&&t.callee.object&&"cssx"===t.callee.object.name)t.callee.object.name=e;else if(u(t))for(i=0;i<t.length;i++)d(t[i],e);else for(s in t)f(s)||"object"==typeof t[s]&&d(t[s],e);return t};t.exports={enter:function(t,e,s,n){i=[],r=c(),n.addToCSSXSelfInvoke=function(t){i=[t].concat(i)}},exit:function(t,e,s,c){delete c.addToCSSXSelfInvoke,i.push(l.variableDeclaration("var",[l.variableDeclarator(l.identifier(r),l.callExpression(l.MemberExpression(l.identifier(h.CSSXCalleeObj),l.identifier(h.CSSXNewStylesheet)),[l.stringLiteral(r)]))])),i=i.concat(t.body.map(function(t){return t=d(t,r),"CallExpression"===t.type&&(t=l.expressionStatement(d(t,r))),t})),i.push(l.returnStatement(l.identifier(r))),n=l.blockStatement(i),a=l.callExpression(l.memberExpression(l.functionExpression(null,[],n),l.identifier("apply")),[l.thisExpression()]), o=l.expressionStatement(a),0===t.body.length?delete e[s]:u(e)?p(e,s,o):e[s]=o}}},function(t,e){t.exports=function(t,e,s){t.splice.apply(t,[e,1].concat(s))}},function(t,e){t.exports={CSSXCalleeObj:"cssx",CSSXCalleeProp:"add",CSSXClientNestedMethodName:"n",CSSXNewStylesheet:"s"}},function(t,e,s){var i=s(41),r=s(390),n=function(t){return i.callExpression(i.MemberExpression(i.identifier(r.CSSXCalleeObj),i.identifier(r.CSSXCalleeProp)),t)};t.exports={enter:function(t,e,s){},exit:function(t,e,s){var i,r=[];return t.selector?r.push(t.selector):null,t.body?r.push(t.body):null,i=n(r),"undefined"!=typeof e&&"undefined"!==s&&(e[s]=i),i}},t.exports.formCSSXElement=n},function(t,e,s){var i=s(41),r=s(393);t.exports={enter:function(t,e,s){},exit:function(t,e,s){t.expressions?e[s]=r(t):e[s]=i.stringLiteral(t.name)}}},function(t,e,s){var i=s(41),r=s(1);t.exports=function(t){var e,s,n,a,o,u,p,c,l=t.value||t.name,h=t.expressions,f=-1,d=!1,y=l.length,m="";for(a=h.map(function(t){return e=l.substr(t.contextLoc.start,t.contextLoc.end-t.contextLoc.start),s="("+e.replace(/^`(.+)`$/,"$1")+")",{start:t.contextLoc.start,end:t.contextLoc.end,replaceWith:s}}),o=a.map(function(t){return t.start}),u=a.map(function(t){return t.end});++f<y;)(p=o.indexOf(f))>=0?(m+=(0===f?"":'" + ')+a[p].replaceWith,d=!0):(p=u.indexOf(f))>=0&&(m+=f===y-1?"":' + "',d=!1),d||(c=l.charAt(f),c='"'===c?'\\"':c,m+=0===f?'"'+c:f===y-1?c+'"':c);try{n=r(m)}catch(v){throw new Error("parsing cssx expression: "+m+" ("+v.message+")")}return n&&n.program&&n.program.body&&n.program.body[0]&&n.program.body[0].expression?n.program.body[0].expression:i.stringLiteral(l)}},function(t,e){t.exports={enter:function(t,e,s){},exit:function(t,e,s){e[s]={key:t.label,value:t.body}}}},function(t,e,s){var i=s(41),r=s(387);t.exports={enter:function(t,e,s,i){},exit:function(t,e,s,n){var a,o,u,p=t.body,c=r();u=function(t){n&&n.addToCSSXSelfInvoke&&n.addToCSSXSelfInvoke(t)},o=i.variableDeclaration("var",[i.variableDeclarator(i.identifier(c),i.objectExpression([]))]),p.forEach(function(t){a=i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(c),t.key,!0),t.value)),u(a)}),u(o),e[s]=i.identifier(c)}}},function(t,e,s){var i=s(41),r=s(393);t.exports={enter:function(t,e,s){},exit:function(t,e,s){t.expressions?e[s]=r(t):e[s]=i.stringLiteral(t.value)}}},function(t,e,s){var i=s(41),r=s(393);t.exports={enter:function(t,e,s){},exit:function(t,e,s){t.expressions?e[s]=r(t):e[s]=i.stringLiteral(t.name)}}},function(t,e,s){var i=s(391),r=i.formCSSXElement,n=s(41),a=s(389),o=s(4),u=s(390),p=s(387);t.exports={enter:function(t,e,s){},exit:function(t,e,s){var i=p(),c=[];c.push(n.variableDeclaration("var",[n.variableDeclarator(n.identifier(i),r([n.stringLiteral(t.query)]))])),c=c.concat(t.body.map(function(t){return t.callee.object.name=i,t.callee.property.name=u.CSSXClientNestedMethodName,n.expressionStatement(t)})),o(e)?a(e,s,c):delete e[s]}}}])}); //# sourceMappingURL=cssxler.min.js.map
ajax/libs/forerunnerdb/1.3.337/fdb-core+views.min.js
humbletim/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/View");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/View":29,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":28}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":27}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){this.init.apply(this,arguments)};e.prototype.init=function(a,b,c,d){this._store=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Sorting"),d.mixin(e.prototype,"Mixin.Common"),d.synthesize(e.prototype,"compareFunc"),d.synthesize(e.prototype,"hashFunc"),d.synthesize(e.prototype,"indexDir"),d.synthesize(e.prototype,"index",function(a){return void 0!==a&&(a instanceof Array||(a=this.keys(a))),this.$super.call(this,a)}),e.prototype.keys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},e.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},e.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},e.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),!0}return!1},e.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._index.length;c++)if(d=this._index[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},e.prototype._hashFunc=function(a){return a[this._index[0].key]},e.prototype.insert=function(a){var b,c,d,f;if(a instanceof Array){for(c=[],d=[],f=0;f<a.length;f++)this.insert(a[f])?c.push(a[f]):d.push(a[f]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new e(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new e(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new e(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},e.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},e.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"key":b.push(this._data);break;default:b.push({key:this._key,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},d.finishModule("BinaryTree"),b.exports=e},{"./Shared":27}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[p]),q=!0;break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this._onChange(),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H=this._metrics.create("find"),I=this.primaryKey(),J=this,K=!0,L={},M=[],N=[],O=[],P={},Q={},R=function(c){return J._match(c,a,b,"and",P)};if(H.start(),a){if(H.time("analyseQuery"),c=this._analyseQuery(J.decouple(a),b,H),H.time("analyseQuery"),H.data("analysis",c),c.hasJoin&&c.queriesJoin){for(H.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],L[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];H.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(H.data("index.potential",c.indexMatch),H.data("index.used",c.indexMatch[0].index),H.time("indexLookup"),e=c.indexMatch[0].lookup||[],H.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(K=!1)):H.flag("usedIndex",!1),K&&(e&&e.length?(d=e.length,H.time("tableScan: "+d),e=e.filter(R)):(d=this._data.length,H.time("tableScan: "+d),e=this._data.filter(R)),H.time("tableScan: "+d)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(Q.page=b.$page,Q.pages=Math.ceil(e.length/b.$limit),Q.records=e.length,b.$page&&b.$limit>0&&(H.data("cursor",Q),e.splice(0,b.$page*b.$limit))),b.$skip&&(Q.skip=b.$skip,e.splice(0,b.$skip),H.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(Q.limit=b.$limit,e.length=b.$limit,H.data("limit",b.$limit)),b.$decouple&&(H.time("decouple"),e=this.decouple(e),H.time("decouple"),H.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=L[k]?L[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=m[n].query),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=J._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else M.push(e[x])}H.data("flag.join",!0)}if(M.length){for(H.time("removalQueue"),z=0;z<M.length;z++)y=e.indexOf(M[z]),y>-1&&e.splice(y,1);H.time("removalQueue")}if(b.$transform){for(H.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));H.time("transform"),H.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(H.time("transformOut"),e=this.transformOut(e),H.time("transformOut")),H.data("results",e.length)}else e=[];H.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?N.push(z):0===b[z]&&O.push(z));if(H.time("scanFields"),N.length||O.length){for(H.data("flag.limitFields",!0),H.data("limitFields.on",N),H.data("limitFields.off",O),H.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(N.length&&A!==I&&-1===N.indexOf(A)&&delete G[A],O.length&&O.indexOf(A)>-1&&delete G[A])}H.time("limitFields")}if(b.$elemMatch){H.data("flag.elemMatch",!0),H.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(J._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}H.time("projection-elemMatch")}if(b.$elemsMatch){H.data("flag.elemsMatch",!0),H.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)J._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}H.time("projection-elemsMatch")}return H.stop(),e.__fdbOp=H,e.$cursor=Q,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g=this;if("string"==typeof a)return"$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b)[0]:new h(a).value(b)[0];c={};for(f in a)if(a.hasOwnProperty(f))switch(d=typeof a[f],e=a[f],d){case"string":"$$."===e.substr(0,3)?c[f]=new h(e.substr(3,e.length-3)).value(b)[0]:c[f]=e;break;case"object":c[f]=g._resolveDynamicQuery(e,b);break;default:c[f]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=String(c),e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c, id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":8,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":27}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(){if(!this.isDropped()){var a,b,c;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":27}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;if(void 0!==a){for(b=0;b<h.length;b++)if(h[b].name===a)return h[b];return void 0}for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":13,"./Overload":24,"./Shared":27}],8:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":13,"./Overload":24,"./Shared":27}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(h.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},i.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},i.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},i.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},i.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},i.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=i},{"./BinaryTree":4,"./Path":25,"./Shared":27}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":25,"./Shared":27}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":27}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":23,"./Shared":27}],14:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}return void 0},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}return void 0},jParse:function(a){return JSON.parse(a)},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":24}],17:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],18:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":24}],19:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){for(k in b)if(b.hasOwnProperty(k)){if(f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or": for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++){if(i[h]instanceof RegExp&&i[h].test(b))return!0;if(i[h]===b)return!0}return!1}throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(l[k]===b)return!1;return!0}throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0}return-1}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":24}],22:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":25,"./Shared":27}],24:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],25:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":27}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":27}],27:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.337",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],28:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],29:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b&&!b.isDropped()&&b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,b._querySettings.options,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,b._querySettings.options,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);return this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(){return this.isDropped()?!0:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),b.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return a instanceof l?a:(this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=l},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":26,"./Shared":27}]},{},[1]);
src/client.js
LinInLiao/LinInLiaoLa
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import Location from 'react-router/lib/Location'; import queryString from 'query-string'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import universalRouter from './helpers/universalRouter'; const history = new BrowserHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(client, window.__data); const search = document.location.search; const query = search && queryString.parse(search); const location = new Location(document.location.pathname, query); universalRouter(location, history, store) .then(({component}) => { if (__DEVTOOLS__) { const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' + ' invalid." message. That\'s because the redux-devtools are enabled.'); React.render(<div> {component} <DebugPanel top right bottom key="debugPanel"> <DevTools store={store} monitor={LogMonitor}/> </DebugPanel> </div>, dest); } else { React.render(component, dest); } }, (error) => { console.error(error); }); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } }
files/rxjs/2.3.24/rx.lite.js
AdityaManohar/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise, }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // 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); } } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + normalizeTime(dueTime); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { var notification = new Notification('E'); notification.exception = e; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch (err) { observer.onError(err); 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.catchError = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch (err) { observer.onError(err); 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; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (observer) { var e; var exceptions = new Subject(); var handled = notificationHandler(exceptions); var notifier = new Subject(); var notificationDisposable = handled.subscribe(notifier); try { e = sources[$iterator$](); } catch (err) { observer.onError(err); 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 outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { inner.setDisposable(notifier.subscribe(function(){ self(); }, function(ex) { observer.onError(ex); }, function() { observer.onCompleted(); })); exceptions.onNext(exn); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { 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 an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var source = this; return new AnonymousObservable(function(observer) { var arr = []; return source.subscribe( function (x) { arr.push(x); }, function (e) { observer.onError(e); }, function () { observer.onNext(arr); observer.onCompleted(); }); }, source); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { if (this._i < this._l) { var val = this._s.charAt(this._i++); return { done: false, value: val }; } else { return doneEnumerator; } }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { if (this._i < this._l) { var val = this._a[this._i++]; return { done: false, value: val }; } else { return doneEnumerator; } }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); var list = Object(iterable), it = getIterable(list); return new AnonymousObservable(function (observer) { var i = 0; return scheduler.scheduleRecursive(function (self) { var next; try { next = it.next(); } catch (e) { observer.onError(e); return; } if (next.done) { observer.onCompleted(); return; } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { //deprecate('fromArray', 'from'); isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; function observableOf (scheduler, array) { 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(); } }); }); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { return observableOf(null, arguments); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { return observableOf(scheduler, slice.call(arguments, 1)); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var idx = 0, keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursive(function (self) { if (idx < len) { var key = keys[idx++]; observer.onNext([key, obj[key]]); self(); } else { observer.onCompleted(); } }); }); }; /** * 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. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { //deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (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; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * @deprecated use #catch or #catchError instead. */ observableProto.catchException = function (handlerOrSecond) { //deprecate('catchException', 'catch or catchError'); return this.catchError(handlerOrSecond); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchError(); }; /** * @deprecated use #catch or #catchError instead. */ Observable.catchException = function () { //deprecate('catchException', 'catch or catchError'); return observableCatch.apply(null, arguments); }; /** * 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); }, function(e) { observer.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = function () { return this.merge(1); }; /** @deprecated Use `concatAll` instead. */ observableProto.concatObservable = function () { //deprecate('concatObservable', 'concatAll'); 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 (o) { 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(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && o.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, function (e) { o.onError(e); }, function () { isStopped = true; activeCount === 0 && o.onCompleted(); })); return group; }, sources); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (isScheduler(arguments[0])) { 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 observableOf(scheduler, sources).mergeAll(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (o) { 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(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && o.onCompleted(); })); }, function (e) { o.onError(e); }, function () { isStopped = true; group.length === 1 && o.onCompleted(); })); return group; }, sources); }; /** * @deprecated use #mergeAll instead. */ observableProto.mergeObservable = function () { //deprecate('mergeObservable', 'mergeAll'); return this.mergeAll.apply(this, arguments); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var source = this; var args = slice.call(arguments); var resultSelector = args.pop(); if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } /** * 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); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var 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); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (e) { o.onError(e); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = function (x) { observerOrOnNext.onNext(x); }; onError = function (e) { observerOrOnNext.onError(e); }; onCompleted = function () { observerOrOnNext.onCompleted(); } } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }, this); }; /** @deprecated use #do or #tap instead. */ observableProto.doAction = function () { //deprecate('doAction', 'do or tap'); return this.tap.apply(this, arguments); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * 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 selectorFn = isFunction(selector) ? bindCallback(selector, thisArg, 3) : function () { return selector; }, source = this; return new AnonymousObservable(function (o) { var count = 0; return source.subscribe(function (value) { try { var result = selectorFn(value, count++, source); } catch (e) { o.onError(e); return; } o.onNext(result); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * 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) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * 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 source = this; predicate = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var count = 0; return source.subscribe(function (value) { try { var shouldRun = predicate(value, count++, source); } catch (e) { o.onError(e); return; } shouldRun && o.onNext(value); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler() { var results = arguments; if (selector) { try { results = selector(results); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (!!root.Ember && typeof root.Ember.addListener === 'function') { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { o.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } if (isDone && values[1]) { o.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { o.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { o.onNext(q.shift()); } o.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; (!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted(); }, onError: function (error) { this.hasFailed = true; this.error = error; (!this.enableQueue || this.queue.length === 0) && this.subject.onError(error); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(value); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while (this.queue.length >= numberOfItems && numberOfItems > 0) { this.subject.onNext(this.queue.shift()); numberOfItems--; } return this.queue.length !== 0 ? { numberOfItems: numberOfItems, returnValue: true } : { numberOfItems: numberOfItems, returnValue: false }; } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); var number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe, parent) { this.source = parent; 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)); 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 { !noError && this.dispose(); } }; AutoDetachObserverPrototype.error = function (err) { try { this.observer.onError(err); } 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 () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.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.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.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); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.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 i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.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 subscribe(observer) { this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
src/components/common/svg-icons/notification/network-locked.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationNetworkLocked = (props) => ( <SvgIcon {...props}> <path d="M19.5 10c.17 0 .33.03.5.05V1L1 20h13v-3c0-.89.39-1.68 1-2.23v-.27c0-2.48 2.02-4.5 4.5-4.5zm2.5 6v-1.5c0-1.38-1.12-2.5-2.5-2.5S17 13.12 17 14.5V16c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 0h-3v-1.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V16z"/> </SvgIcon> ); NotificationNetworkLocked = pure(NotificationNetworkLocked); NotificationNetworkLocked.displayName = 'NotificationNetworkLocked'; NotificationNetworkLocked.muiName = 'SvgIcon'; export default NotificationNetworkLocked;
test/LabelSpec.js
Azerothian/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Label from '../src/Label'; describe('Label', function () { it('Should output a label with message', function () { let instance = ReactTestUtils.renderIntoDocument( <Label> <strong>Message</strong> </Label> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong')); }); it('Should have bsClass by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Label> Message </Label> ); assert.ok(instance.getDOMNode().className.match(/\blabel\b/)); }); it('Should have bsStyle by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Label> Message </Label> ); assert.ok(instance.getDOMNode().className.match(/\blabel-default\b/)); }); });
website/server/generate.js
Ehesp/react-native
/** * 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. */ 'use strict'; var Promise = require('bluebird'); var request = require('request'); var glob = require('glob'); var fs = require('fs.extra'); var mkdirp = require('mkdirp'); var server = require('./server.js'); var Feed = require('feed'); require('./convert.js')({extractDocs: true}); server.noconvert = true; // Sadly, our setup fatals when doing multiple concurrent requests // I don't have the time to dig into why, it's easier to just serialize // requests. var queue = Promise.resolve(); // Generate RSS Feeds queue = queue.then(function() { return new Promise(function(resolve, reject) { var targetFile = 'build/react-native/blog/feed.xml'; var basePath = 'https://facebook.github.io/react-native/'; var blogPath = basePath + 'blog/'; var metadataBlog = JSON.parse(fs.readFileSync('server/metadata-blog.json')); var latestPost = metadataBlog.files[0]; var feed = new Feed({ title: 'React Native Blog', description: 'The best place to stay up-to-date with the latest React Native news and events.', id: blogPath, link: blogPath, image: basePath + 'img/header_logo.png', copyright: 'Copyright © ' + new Date().getFullYear() + ' Facebook Inc.', updated: new Date(latestPost.publishedAt), }); metadataBlog.files.forEach(function(post) { var url = blogPath + post.path; feed.addItem({ title: post.title, id: url, link: url, date: new Date(post.publishedAt), author: [{ name: post.author, link: post.authorURL }], description: post.excerpt, }); }); mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), '')); fs.writeFileSync(targetFile, feed.render('atom-1.0')); console.log('Generated RSS feed') resolve(); }); }); // Generate HTML for each non-source code JS file glob('src/**/*.*', function(er, files) { files.forEach(function(file) { var targetFile = file.replace(/^src/, 'build'); if (file.match(/\.js$/) && !file.match(/src\/react-native\/js/)) { targetFile = targetFile.replace(/\.js$/, '.html'); queue = queue.then(function() { return new Promise(function(resolve, reject) { request('http://localhost:8079/' + targetFile.replace(/^build\//, ''), function(error, response, body) { if (error) { reject(error); return; } if (response.statusCode != 200) { reject(new Error('Status ' + response.statusCode + ':\n' + body)); return; } mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), '')); fs.writeFileSync(targetFile, body); resolve(); }); }); }); } else { queue = queue.then(function() { return new Promise(function(resolve, reject) { mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), '')); fs.copy(file, targetFile, resolve); }); }); } }); queue = queue.then(function() { console.log('Generated HTML files from JS'); }).finally(function() { server.close(); }).catch(function(e) { console.error(e); process.exit(1); }); });
project/react-hooks-ant4-ts/src/__test__/component/deep/index.js
FFF-team/generator-earth
import React from 'react'; import C from './c'; export default class Index extends React.Component { render() { return ( <div className="index" onClick={this.props.onClick}> <C /> </div> ) } }
src/js/product.js
AlexBai1991/learning-react
'use strict'; import React from 'react'; import ReactDom from 'react-dom'; const PRODUCTS = [ { name: '足球', price: '¥49.99', category: '体育用品', stocked: true }, { name: '棒球', price: '¥39.99', category: '体育用品', stocked: false }, { name: '篮球', price: '¥69.99', category: '体育用品', stocked: true }, { name: 'IPhone 6s plus', price: '¥5899.00', category: '电子产品', stocked: false }, { name: 'Samsung Galaxy S7', price: '¥6089.00', category: '电子产品', stocked: true }, { name: 'Google Nexus 7', price: '¥4889.00', category: '电子产品', stocked: false } ]; /** * @Structure * * FilterableProductTable * SearchBar * ProductTable * ProductCategoryRow * ProductRow */ // SearchBar let SearchBar = React.createClass({ handleChange() { this.props.onUserInput( this.refs.filterTextInput.value, this.refs.isStockOnlyInput.checked ); }, render() { return ( <form> <input type="text" placeholder="Search..." value={this.props.filterText} ref="filterTextInput" onChange={this.handleChange} /> <br/> <label style={{cursor: 'pointer'}}> <input type="checkbox" checked={this.props.isStockOnly} ref="isStockOnlyInput" onChange={this.handleChange} /> Only show products in stock </label> </form> ); } }); // ProductCategoryRow let ProductCategoryRow = React.createClass({ render() { return ( <tr> <th colSpan="2">{this.props.category}</th> </tr> ); } }); // ProductRow let ProductRow = React.createClass({ render() { let name = !this.props.product.stocked ? this.props.product.name : <span style={{color: 'red'}}>{this.props.product.name}</span> return ( <tr> <td>{name}</td> <td>{this.props.product.price}</td> </tr> ); } }); // ProductTable let ProductTable = React.createClass({ // filterText render() { let rows = [], lastCategory = null; let products = this.props.products; products.forEach(product => { // 只展现filter的商品 if (product.name.indexOf(this.props.filterText) === -1 || (this.props.isStockOnly && !product.stocked)) { return; } if (product.category !== lastCategory) { rows.push(<ProductCategoryRow category={product.category} key={product.category} />); } rows.push(<ProductRow product={product} key={product.name} />); lastCategory = product.category; }); return ( <table cellSpacing="0"> <thead> <tr> <th>名字</th> <th>价格</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } }); // FilterableProductTable let FilterableProductTable = React.createClass({ getInitialState() { return { filterText: '', isStockOnly: false }; }, handleUserInput(filterText, isStockOnly) { this.setState({ filterText: filterText, isStockOnly: isStockOnly }); }, render() { return ( <div className="filterable-product-table"> <h1>Filterable Product Table</h1> <SearchBar filterText={this.state.filterText} isStockOnly={this.state.isStockOnly} onUserInput={this.handleUserInput} /> <ProductTable products={this.props.products} filterText={this.state.filterText} isStockOnly={this.state.isStockOnly} /> </div> ); } }); // render ReactDom.render( <FilterableProductTable products={PRODUCTS}/>, document.querySelector('#example') );
src/components/DataTable/stories/with-dynamic-content.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import Delete from '@carbon/icons-react/lib/delete/16'; import Save from '@carbon/icons-react/lib/save/16'; import Download from '@carbon/icons-react/lib/download/16'; import DataTable, { Table, TableBatchAction, TableBatchActions, TableBody, TableCell, TableContainer, TableExpandHeader, TableExpandRow, TableExpandedRow, TableHead, TableHeader, TableRow, TableSelectAll, TableSelectRow, TableToolbar, TableToolbarAction, TableToolbarContent, TableToolbarSearch, TableToolbarMenu, } from '../../DataTable'; import { batchActionClick, initialRows, headers } from './shared'; export default props => { const insertInRandomPosition = (array, element) => { const index = Math.floor(Math.random() * (array.length + 1)); return [...array.slice(0, index), element, ...array.slice(index)]; }; class DynamicRows extends React.Component { state = { rows: initialRows, headers: headers, id: 0, }; handleOnHeaderAdd = () => { const length = this.state.headers.length; const header = { key: `header_${length}`, header: `Header ${length}`, }; this.setState(state => { const rows = state.rows.map(row => { return { ...row, [header.key]: header.header, }; }); return { rows, headers: state.headers.concat(header), }; }); }; handleOnRowAdd = () => { this.setState(state => { const { id: _id, rows } = state; const id = _id + 1; const row = { id: '' + id, name: `New Row ${id}`, protocol: 'HTTP', port: id * 100, rule: id % 2 === 0 ? 'Round robin' : 'DNS delegation', attached_groups: `Row ${id}'s VM Groups`, status: 'Starting', }; state.headers .filter(header => row[header.key] === undefined) .forEach(header => { row[header.key] = header.header; }); return { id, rows: insertInRandomPosition(rows, row), }; }); }; render() { return ( <DataTable rows={this.state.rows} headers={this.state.headers} {...this.props} render={({ rows, headers, getHeaderProps, getSelectionProps, getBatchActionProps, getRowProps, onInputChange, selectedRows, getTableProps, }) => ( <TableContainer title="DataTable" description="Use the toolbar menu to add rows and headers"> <TableToolbar> <TableBatchActions {...getBatchActionProps()}> <TableBatchAction renderIcon={Delete} iconDescription="Delete the selected rows" onClick={batchActionClick(selectedRows)}> Delete </TableBatchAction> <TableBatchAction renderIcon={Save} iconDescription="Save the selected rows" onClick={batchActionClick(selectedRows)}> Save </TableBatchAction> <TableBatchAction renderIcon={Download} iconDescription="Download the selected rows" onClick={batchActionClick(selectedRows)}> Download </TableBatchAction> </TableBatchActions> <TableToolbarContent> <TableToolbarSearch onChange={onInputChange} /> <TableToolbarMenu> <TableToolbarAction onClick={this.handleOnRowAdd}> Add row </TableToolbarAction> <TableToolbarAction onClick={this.handleOnHeaderAdd}> Add header </TableToolbarAction> </TableToolbarMenu> </TableToolbarContent> </TableToolbar> <Table {...getTableProps()}> <TableHead> <TableRow> <TableExpandHeader /> <TableSelectAll {...getSelectionProps()} /> {headers.map(header => ( <TableHeader {...getHeaderProps({ header })}> {header.header} </TableHeader> ))} </TableRow> </TableHead> <TableBody> {rows.map(row => ( <React.Fragment key={row.id}> <TableExpandRow {...getRowProps({ row })}> <TableSelectRow {...getSelectionProps({ row })} /> {row.cells.map(cell => ( <TableCell key={cell.id}>{cell.value}</TableCell> ))} </TableExpandRow> <TableExpandedRow colSpan={headers.length + 3}> <h1>Expandable row content</h1> <p>Description here</p> </TableExpandedRow> </React.Fragment> ))} </TableBody> </Table> </TableContainer> )} /> ); } } return <DynamicRows {...props} />; };
ajax/libs/js-data/1.0.0-alpha.5-1/js-data.js
brix/cdnjs
/** * @author Jason Dobry <[email protected]> * @file js-data.js * @version 1.0.0-alpha.5-1 - Homepage <http://www.js-data.io/> * @copyright (c) 2014 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Data store. */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSData=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Modifications // Copyright 2014 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function diffObjectFromOldObject(object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ var eomObj = { pingPong: true }; var eomRunScheduled = false; Object.observe(eomObj, function() { runEOMTasks(); eomRunScheduled = false; }); return function(fn) { eomTasks.push(fn); if (!eomRunScheduled) { eomRunScheduled = true; eomObj.pingPong = !eomObj.pingPong; } }; })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = hasObserve && hasEval && (function() { try { eval('%RunMicrotasks()'); return true; } catch (ex) { return false; } })(); global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { eval('%RunMicrotasks()'); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, 'delete': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } global.Observer = Observer; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })(exports); },{}],2:[function(require,module,exports){ (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.0 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver @param {String} label optional string for labeling the promise. Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver, label) { this._id = $$es6$promise$promise$$counter++; this._label = label; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection, label) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } parent._onerror = null; var child = new this.constructor($$$internal$$noop, label); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'catch': function(onRejection, label) { return this.then(null, onRejection, label); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { Promise: $$es6$promise$promise$$default, polyfill: $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if (typeof define === 'function' && define['amd']) { define(function() { return es6$promise$umd$$ES6Promise; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":3}],3:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],4:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":9}],5:[function(require,module,exports){ var makeIterator = require('../function/makeIterator_'); /** * Array filter */ function filter(arr, callback, thisObj) { callback = makeIterator(callback, thisObj); var results = []; if (arr == null) { return results; } var i = -1, len = arr.length, value; while (++i < len) { value = arr[i]; if (callback(value, i, arr)) { results.push(value); } } return results; } module.exports = filter; },{"../function/makeIterator_":16}],6:[function(require,module,exports){ var findIndex = require('./findIndex'); /** * Returns first item that matches criteria */ function find(arr, iterator, thisObj){ var idx = findIndex(arr, iterator, thisObj); return idx >= 0? arr[idx] : void(0); } module.exports = find; },{"./findIndex":7}],7:[function(require,module,exports){ var makeIterator = require('../function/makeIterator_'); /** * Returns the index of the first item that matches criteria */ function findIndex(arr, iterator, thisObj){ iterator = makeIterator(iterator, thisObj); if (arr == null) { return -1; } var i = -1, len = arr.length; while (++i < len) { if (iterator(arr[i], i, arr)) { return i; } } return -1; } module.exports = findIndex; },{"../function/makeIterator_":16}],8:[function(require,module,exports){ /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; },{}],9:[function(require,module,exports){ /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; },{}],10:[function(require,module,exports){ var filter = require('./filter'); function isValidString(val) { return (val != null && val !== ''); } /** * Joins strings with the specified separator inserted between each value. * Null values and empty strings will be excluded. */ function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } module.exports = join; },{"./filter":5}],11:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; },{"./indexOf":9}],12:[function(require,module,exports){ /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; },{}],13:[function(require,module,exports){ /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; },{}],14:[function(require,module,exports){ var isFunction = require('../lang/isFunction'); /** * Creates an object that holds a lookup for the objects in the array. */ function toLookup(arr, key) { var result = {}; if (arr == null) { return result; } var i = -1, len = arr.length, value; if (isFunction(key)) { while (++i < len) { value = arr[i]; result[key(value)] = value; } } else { while (++i < len) { value = arr[i]; result[value[key]] = value; } } return result; } module.exports = toLookup; },{"../lang/isFunction":23}],15:[function(require,module,exports){ /** * Returns the first argument provided to it. */ function identity(val){ return val; } module.exports = identity; },{}],16:[function(require,module,exports){ var identity = require('./identity'); var prop = require('./prop'); var deepMatches = require('../object/deepMatches'); /** * Converts argument into a valid iterator. * Used internally on most array/object/collection methods that receives a * callback/iterator providing a shortcut syntax. */ function makeIterator(src, thisObj){ if (src == null) { return identity; } switch(typeof src) { case 'function': // function is the first to improve perf (most common case) // also avoid using `Function#call` if not needed, which boosts // perf a lot in some cases return (typeof thisObj !== 'undefined')? function(val, i, arr){ return src.call(thisObj, val, i, arr); } : src; case 'object': return function(val){ return deepMatches(val, src); }; case 'string': case 'number': return prop(src); } } module.exports = makeIterator; },{"../object/deepMatches":32,"./identity":15,"./prop":17}],17:[function(require,module,exports){ /** * Returns a function that gets a property of the passed object */ function prop(name){ return function(obj){ return obj[name]; }; } module.exports = prop; },{}],18:[function(require,module,exports){ var kindOf = require('./kindOf'); var isPlainObject = require('./isPlainObject'); var mixIn = require('../object/mixIn'); /** * Clone native types. */ function clone(val){ switch (kindOf(val)) { case 'Object': return cloneObject(val); case 'Array': return cloneArray(val); case 'RegExp': return cloneRegExp(val); case 'Date': return cloneDate(val); default: return val; } } function cloneObject(source) { if (isPlainObject(source)) { return mixIn({}, source); } else { return source; } } function cloneRegExp(r) { var flags = ''; flags += r.multiline ? 'm' : ''; flags += r.global ? 'g' : ''; flags += r.ignorecase ? 'i' : ''; return new RegExp(r.source, flags); } function cloneDate(date) { return new Date(+date); } function cloneArray(arr) { return arr.slice(); } module.exports = clone; },{"../object/mixIn":38,"./isPlainObject":27,"./kindOf":30}],19:[function(require,module,exports){ var clone = require('./clone'); var forOwn = require('../object/forOwn'); var kindOf = require('./kindOf'); var isPlainObject = require('./isPlainObject'); /** * Recursively clone native types. */ function deepClone(val, instanceClone) { switch ( kindOf(val) ) { case 'Object': return cloneObject(val, instanceClone); case 'Array': return cloneArray(val, instanceClone); default: return clone(val); } } function cloneObject(source, instanceClone) { if (isPlainObject(source)) { var out = {}; forOwn(source, function(val, key) { this[key] = deepClone(val, instanceClone); }, out); return out; } else if (instanceClone) { return instanceClone(source); } else { return source; } } function cloneArray(arr, instanceClone) { var out = [], i = -1, n = arr.length, val; while (++i < n) { out[i] = deepClone(arr[i], instanceClone); } return out; } module.exports = deepClone; },{"../object/forOwn":35,"./clone":18,"./isPlainObject":27,"./kindOf":30}],20:[function(require,module,exports){ var isKind = require('./isKind'); /** */ var isArray = Array.isArray || function (val) { return isKind(val, 'Array'); }; module.exports = isArray; },{"./isKind":24}],21:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isBoolean(val) { return isKind(val, 'Boolean'); } module.exports = isBoolean; },{"./isKind":24}],22:[function(require,module,exports){ var forOwn = require('../object/forOwn'); var isArray = require('./isArray'); function isEmpty(val){ if (val == null) { // typeof null == 'object' so we check it first return true; } else if ( typeof val === 'string' || isArray(val) ) { return !val.length; } else if ( typeof val === 'object' ) { var result = true; forOwn(val, function(){ result = false; return false; // break loop }); return result; } else { return true; } } module.exports = isEmpty; },{"../object/forOwn":35,"./isArray":20}],23:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isFunction(val) { return isKind(val, 'Function'); } module.exports = isFunction; },{"./isKind":24}],24:[function(require,module,exports){ var kindOf = require('./kindOf'); /** * Check if value is from a specific "kind". */ function isKind(val, kind){ return kindOf(val) === kind; } module.exports = isKind; },{"./kindOf":30}],25:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isNumber(val) { return isKind(val, 'Number'); } module.exports = isNumber; },{"./isKind":24}],26:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isObject(val) { return isKind(val, 'Object'); } module.exports = isObject; },{"./isKind":24}],27:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],28:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isRegExp(val) { return isKind(val, 'RegExp'); } module.exports = isRegExp; },{"./isKind":24}],29:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isString(val) { return isKind(val, 'String'); } module.exports = isString; },{"./isKind":24}],30:[function(require,module,exports){ var _rKind = /^\[object (.*)\]$/, _toString = Object.prototype.toString, UNDEF; /** * Gets the "kind" of value. (e.g. "String", "Number", etc) */ function kindOf(val) { if (val === null) { return 'Null'; } else if (val === UNDEF) { return 'Undefined'; } else { return _rKind.exec( _toString.call(val) )[1]; } } module.exports = kindOf; },{}],31:[function(require,module,exports){ /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; },{}],32:[function(require,module,exports){ var forOwn = require('./forOwn'); var isArray = require('../lang/isArray'); function containsMatch(array, pattern) { var i = -1, length = array.length; while (++i < length) { if (deepMatches(array[i], pattern)) { return true; } } return false; } function matchArray(target, pattern) { var i = -1, patternLength = pattern.length; while (++i < patternLength) { if (!containsMatch(target, pattern[i])) { return false; } } return true; } function matchObject(target, pattern) { var result = true; forOwn(pattern, function(val, key) { if (!deepMatches(target[key], val)) { // Return false to break out of forOwn early return (result = false); } }); return result; } /** * Recursively check if the objects match. */ function deepMatches(target, pattern){ if (target && typeof target === 'object') { if (isArray(target) && isArray(pattern)) { return matchArray(target, pattern); } else { return matchObject(target, pattern); } } else { return target === pattern; } } module.exports = deepMatches; },{"../lang/isArray":20,"./forOwn":35}],33:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; },{"../lang/isPlainObject":27,"./forOwn":35}],34:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; },{"./hasOwn":36}],35:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; },{"./forIn":34,"./hasOwn":36}],36:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],37:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var deepClone = require('../lang/deepClone'); var isObject = require('../lang/isObject'); /** * Deep merge objects. */ function merge() { var i = 1, key, val, obj, target; // make sure we don't modify source element and it's properties // objects are passed by reference target = deepClone( arguments[0] ); while (obj = arguments[i++]) { for (key in obj) { if ( ! hasOwn(obj, key) ) { continue; } val = obj[key]; if ( isObject(val) && isObject(target[key]) ){ // inception, deep merge objects target[key] = merge(target[key], val); } else { // make sure arrays, regexp, date, objects are cloned target[key] = deepClone(val); } } } return target; } module.exports = merge; },{"../lang/deepClone":19,"../lang/isObject":26,"./hasOwn":36}],38:[function(require,module,exports){ var forOwn = require('./forOwn'); /** * Combine properties from all the objects into first one. * - This method affects target object in place, if you want to create a new Object pass an empty object as first param. * @param {object} target Target Object * @param {...object} objects Objects to be combined (0...n objects). * @return {object} Target Object. */ function mixIn(target, objects){ var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj != null) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key){ this[key] = val; } module.exports = mixIn; },{"./forOwn":35}],39:[function(require,module,exports){ var forEach = require('../array/forEach'); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; },{"../array/forEach":8}],40:[function(require,module,exports){ var slice = require('../array/slice'); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; },{"../array/slice":12}],41:[function(require,module,exports){ var namespace = require('./namespace'); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; },{"./namespace":39}],42:[function(require,module,exports){ var toString = require('../lang/toString'); var replaceAccents = require('./replaceAccents'); var removeNonWord = require('./removeNonWord'); var upperCase = require('./upperCase'); var lowerCase = require('./lowerCase'); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; },{"../lang/toString":31,"./lowerCase":43,"./removeNonWord":46,"./replaceAccents":47,"./upperCase":48}],43:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; },{"../lang/toString":31}],44:[function(require,module,exports){ var join = require('../array/join'); var slice = require('../array/slice'); /** * Group arguments as path segments, if any of the args is `null` or an * empty string it will be ignored from resulting path. */ function makePath(var_args){ var result = join(slice(arguments), '/'); // need to disconsider duplicate '/' after protocol (eg: 'http://') return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } module.exports = makePath; },{"../array/join":10,"../array/slice":12}],45:[function(require,module,exports){ var toString = require('../lang/toString'); var camelCase = require('./camelCase'); var upperCase = require('./upperCase'); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; },{"../lang/toString":31,"./camelCase":42,"./upperCase":48}],46:[function(require,module,exports){ var toString = require('../lang/toString'); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; },{"../lang/toString":31}],47:[function(require,module,exports){ var toString = require('../lang/toString'); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; },{"../lang/toString":31}],48:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":31}],49:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function create(resourceName, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; options = options || {}; attrs = attrs || {}; var promise = new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(attrs)) { reject(new DSErrors.IA('"attrs" must be an object!')); } else { options = DSUtils._(definition, options); resolve(attrs); } }); if (definition && options.upsert && attrs[definition.idAttribute]) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } else { return promise .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeCreate', DSUtils.merge({}, attrs)); } return _this.getAdapter(options).create(definition, attrs, options); }) .then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterCreate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { var created = _this.inject(definition.name, attrs, options); var id = created[definition.idAttribute]; _this.store[resourceName].completedQueries[id] = new Date().getTime(); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } } module.exports = create; },{"../../errors":70,"../../utils":72}],50:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroy(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R('id "' + id + '" not found in cache!')); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); resolve(item); } }) .then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeDestroy', DSUtils.merge({}, attrs)); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }) .then(function () { return options.afterDestroy.call(item, options, item); }) .then(function (item) { if (options.notify) { _this.emit(options, 'afterDestroy', DSUtils.merge({}, item)); } _this.eject(resourceName, id); return id; })['catch'](function (err) { if (options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } throw err; }); } module.exports = destroy; },{"../../errors":70,"../../utils":72}],51:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroyAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var ejected, toEject; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(params)) { reject(new DSErrors.IA('"params" must be an object!')); } else { options = DSUtils._(definition, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { _this.emit(options, 'beforeDestroy', toEject); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { _this.emit(options, 'afterDestroy', toEject); } return ejected || _this.ejectAll(resourceName, params); })['catch'](function (err) { if (options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } throw err; }); } module.exports = destroyAll; },{"../../errors":70,"../../utils":72}],52:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function find(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries) { resolve(_this.get(resourceName, id)); } else { resolve(); } } }).then(function (item) { if (!(id in resource.completedQueries)) { if (!(id in resource.pendingQueries)) { resource.pendingQueries[id] = _this.getAdapter(options).find(definition, id, options) .then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { resource.completedQueries[id] = new Date().getTime(); return _this.inject(resourceName, data, options); } else { return _this.createInstance(resourceName, data, options); } }); } return resource.pendingQueries[id]; } else { return item; } })['catch'](function (err) { delete resource.pendingQueries[id]; throw err; }); } module.exports = find; },{"../../errors":70,"../../utils":72}],53:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function processResults(data, resourceName, queryHash, options) { var _this = this; var resource = _this.store[resourceName]; var idAttribute = _this.definitions[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options); // Make sure each object is added to completedQueries if (DSUtils.isArray(injected)) { DSUtils.forEach(injected, function (item) { if (item && item[idAttribute]) { resource.completedQueries[item[idAttribute]] = date; } }); } else { console.warn(errorPrefix(resourceName) + 'response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var queryHash; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.definitions[resourceName]) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(params)) { reject(new DSErrors.IA('"params" must be an object!')); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; } if (queryHash in resource.completedQueries) { resolve(_this.filter(resourceName, params, options)); } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { resource.pendingQueries[queryHash] = _this.getAdapter(options).findAll(definition, params, options) .then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { return processResults.call(_this, data, resourceName, queryHash, options); } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })['catch'](function (err) { delete resource.pendingQueries[queryHash]; throw err; }); } module.exports = findAll; },{"../../errors":70,"../../utils":72}],54:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function reap(resourceName, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty('notify')) { options.notify = false; } var items = []; var now = new Date().getTime(); var expiredItem; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { _this.emit(definition, 'beforeReap', items); } if (options.reapAction === 'inject') { DSUtils.forEach(items, function (item) { var id = item[definition.idAttribute]; resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); }); } else if (options.reapAction === 'eject') { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === 'refresh') { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return DSUtils.Promise.all(tasks); } return items; }).then(function (items) { if (options.isInterval || options.notify) { _this.emit(definition, 'afterReap', items); } return items; }); } function refresh(resourceName, id, options) { var _this = this; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.definitions[resourceName]; id = DSUtils.resolveId(_this.definitions[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); options.bypassCache = true; resolve(_this.get(resourceName, id)); } }).then(function (item) { if (item) { return _this.find(resourceName, id, options); } else { return item; } }); } module.exports = { create: require('./create'), destroy: require('./destroy'), destroyAll: require('./destroyAll'), find: require('./find'), findAll: require('./findAll'), loadRelations: require('./loadRelations'), reap: reap, refresh: refresh, save: require('./save'), update: require('./update'), updateAll: require('./updateAll') }; },{"../../errors":70,"../../utils":72,"./create":49,"./destroy":50,"./destroyAll":51,"./find":52,"./findAll":53,"./loadRelations":55,"./save":56,"./update":57,"./updateAll":58}],55:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function loadRelations(resourceName, instance, relations, options) { var _this = this; var definition = _this.definitions[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils.isString(instance) || DSUtils.isNumber(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils.isString(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(instance)) { reject(new DSErrors.IA('"instance(id)" must be a string, number or object!')); } else if (!DSUtils.isArray(relations)) { reject(new DSErrors.IA('"relations" must be a string or an array!')); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty('findBelongsTo')) { options.findBelongsTo = true; } if (!options.hasOwnProperty('findHasMany')) { options.findHasMany = true; } var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (DSUtils.contains(relations, relationName)) { var task; var params = {}; if (options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { '==': instance[definition.idAttribute] }; } if (def.type === 'hasMany' && params[def.foreignKey]) { task = _this.findAll(relationName, params, options); } else if (def.type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, options).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); resolve(tasks); } }) .then(function (tasks) { return DSUtils.Promise.all(tasks); }) .then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } module.exports = loadRelations; },{"../../errors":70,"../../utils":72}],56:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function save(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R('id "' + id + '" not found in cache!')); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.merge({}, attrs)); } if (options.changesOnly) { var resource = _this.store[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, attrs, options); } else { return attrs; } }); } module.exports = save; },{"../../errors":70,"../../utils":72}],57:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function update(resourceName, id, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.merge({}, attrs)); } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, attrs, options); } else { return attrs; } }); } module.exports = update; },{"../../errors":70,"../../utils":72}],58:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function updateAll(resourceName, attrs, params, options) { var _this = this; var definition = _this.definitions[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.merge({}, attrs)); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (data) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, data, options); } else { return data; } }); } module.exports = updateAll; },{"../../errors":70,"../../utils":72}],59:[function(require,module,exports){ var DSUtils = require('../utils'); var DSErrors = require('../errors'); var syncMethods = require('./sync_methods'); var asyncMethods = require('./async_methods'); var observe = require('../../lib/observe-js/observe-js'); var Schemator; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(orderBy, index, a, b) { var def = orderBy[index]; var cA = a[def[0]], cB = b[def[0]]; if (DSUtils.isString(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils.isString(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } } function Defaults() { } var defaultsPrototype = Defaults.prototype; defaultsPrototype.idAttribute = 'id'; defaultsPrototype.basePath = ''; defaultsPrototype.endpoint = ''; defaultsPrototype.useClass = true; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.defaultAdapter = 'http'; defaultsPrototype.loadFromServer = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.bypassCache = false; defaultsPrototype.ignoreMissing = false; defaultsPrototype.findInverseLinks = false; defaultsPrototype.findBelongsTo = false; defaultsPrototype.findHasOn = false; defaultsPrototype.findHasMany = false; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.reapAction = !!DSUtils.w ? 'inject' : 'none'; defaultsPrototype.maxAge = false; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var _this = this; var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; params = params || {}; options = options || {}; if (DSUtils.isObject(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils.isString(clause)) { clause = { '===': clause }; } else if (DSUtils.isNumber(clause) || DSUtils.isBoolean(clause)) { clause = { '==': clause }; } if (DSUtils.isObject(clause)) { DSUtils.forOwn(clause, function (val, op) { if (op === '==') { keep = first ? (attrs[field] == val) : keep && (attrs[field] == val); } else if (op === '===') { keep = first ? (attrs[field] === val) : keep && (attrs[field] === val); } else if (op === '!=') { keep = first ? (attrs[field] != val) : keep && (attrs[field] != val); } else if (op === '!==') { keep = first ? (attrs[field] !== val) : keep && (attrs[field] !== val); } else if (op === '>') { keep = first ? (attrs[field] > val) : keep && (attrs[field] > val); } else if (op === '>=') { keep = first ? (attrs[field] >= val) : keep && (attrs[field] >= val); } else if (op === '<') { keep = first ? (attrs[field] < val) : keep && (attrs[field] < val); } else if (op === '<=') { keep = first ? (attrs[field] <= val) : keep && (attrs[field] <= val); } else if (op === 'in') { if (DSUtils.isString(val)) { keep = first ? val.indexOf(attrs[field]) !== -1 : keep && val.indexOf(attrs[field]) !== -1; } else { keep = first ? DSUtils.contains(val, attrs[field]) : keep && DSUtils.contains(val, attrs[field]); } } else if (op === 'notIn') { if (DSUtils.isString(val)) { keep = first ? val.indexOf(attrs[field]) === -1 : keep && val.indexOf(attrs[field]) === -1; } else { keep = first ? !DSUtils.contains(val, attrs[field]) : keep && !DSUtils.contains(val, attrs[field]); } } else if (op === '|==') { keep = first ? (attrs[field] == val) : keep || (attrs[field] == val); } else if (op === '|===') { keep = first ? (attrs[field] === val) : keep || (attrs[field] === val); } else if (op === '|!=') { keep = first ? (attrs[field] != val) : keep || (attrs[field] != val); } else if (op === '|!==') { keep = first ? (attrs[field] !== val) : keep || (attrs[field] !== val); } else if (op === '|>') { keep = first ? (attrs[field] > val) : keep || (attrs[field] > val); } else if (op === '|>=') { keep = first ? (attrs[field] >= val) : keep || (attrs[field] >= val); } else if (op === '|<') { keep = first ? (attrs[field] < val) : keep || (attrs[field] < val); } else if (op === '|<=') { keep = first ? (attrs[field] <= val) : keep || (attrs[field] <= val); } else if (op === '|in') { if (DSUtils.isString(val)) { keep = first ? val.indexOf(attrs[field]) !== -1 : keep || val.indexOf(attrs[field]) !== -1; } else { keep = first ? DSUtils.contains(val, attrs[field]) : keep || DSUtils.contains(val, attrs[field]); } } else if (op === '|notIn') { if (DSUtils.isString(val)) { keep = first ? val.indexOf(attrs[field]) === -1 : keep || val.indexOf(attrs[field]) === -1; } else { keep = first ? !DSUtils.contains(val, attrs[field]) : keep || !DSUtils.contains(val, attrs[field]); } } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils.isString(params.orderBy)) { orderBy = [ [params.orderBy, 'ASC'] ]; } else if (DSUtils.isArray(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils.isString(params.sort)) { orderBy = [ [params.sort, 'ASC'] ]; } else if (!orderBy && DSUtils.isArray(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils.isString(def)) { orderBy[i] = [def, 'ASC']; } else if (!DSUtils.isArray(def)) { throw new _this.errors.IllegalArgumentError('DS.filter(resourceName[, params][, options]): ' + DSUtils.toJson(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); } var limit = DSUtils.isNumber(params.limit) ? params.limit : null; var skip = null; if (DSUtils.isNumber(params.skip)) { skip = params.skip; } else if (DSUtils.isNumber(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils.isNumber(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils.isNumber(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; function DS(options) { options = options || {}; try { Schemator = require('js-data-schema'); } catch (e) { } if (!Schemator) { try { Schemator = window.Schemator; } catch (e) { } } if (Schemator || options.schemator) { this.schemator = options.schemator || new Schemator(); } this.store = {}; this.definitions = {}; this.adapters = {}; this.defaults = new Defaults(); this.observe = observe; DSUtils.deepMixIn(this.defaults, options); } var dsPrototype = DS.prototype; dsPrototype.getAdapter = function (options) { options = options || {}; return this.adapters[options.adapter] || this.adapters[options.defaultAdapter]; }; dsPrototype.registerAdapter = function (name, Adapter, options) { options = options || {}; if (DSUtils.isFunction(Adapter)) { this.adapters[name] = new Adapter(options); } else { this.adapters[name] = Adapter; } if (options.default) { this.defaults.defaultAdapter = name; } }; dsPrototype.emit = function (definition, event) { var args = Array.prototype.slice.call(arguments, 2); args.unshift(definition.name); args.unshift('DS.' + event); definition.emit.apply(definition, args); }; dsPrototype.errors = require('../errors'); dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; },{"../../lib/observe-js/observe-js":1,"../errors":70,"../utils":72,"./async_methods":54,"./sync_methods":64,"js-data-schema":"js-data-schema"}],60:[function(require,module,exports){ /*jshint evil:true, loopfunc:true*/ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function Resource(options) { DSUtils.deepMixIn(this, options); if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } } var instanceMethods = [ 'compute', 'refresh', 'save', 'update', 'destroy', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'link', 'linkInverse', 'previous', 'unlinkInverse' ]; function defineResource(definition) { var _this = this; var definitions = _this.definitions; if (DSUtils.isString(definition)) { definition = { name: definition.replace(/\s/gi, '') }; } if (!DSUtils.isObject(definition)) { throw new DSErrors.IA('"definition" must be an object!'); } else if (!DSUtils.isString(definition.name)) { throw new DSErrors.IA('"name" must be a string!'); } else if (_this.store[definition.name]) { throw new DSErrors.R(definition.name + ' is already registered!'); } try { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); var def = definitions[definition.name]; if (!DSUtils.isString(def.idAttribute)) { throw new DSErrors.IA('"idAttribute" must be a string!'); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils.isArray(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.name; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; } }); }); } if (typeof Object.freeze === 'function') { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getEndpoint = function (attrs, options) { options = DSUtils.deepMixIn({}, options); var parent = this.parent; var parentKey = this.parentKey; var item; var endpoint; var thisEndpoint = options.endpoint || this.endpoint; var parentDef = definitions[parent]; delete options.endpoint; options = options || {}; options.params = options.params || {}; if (parent && parentKey && parentDef && options.params[parentKey] !== false) { if (DSUtils.isNumber(attrs) || DSUtils.isString(attrs)) { item = _this.get(this.name, attrs); } if (DSUtils.isObject(attrs) && parentKey in attrs) { delete options.params[parentKey]; endpoint = DSUtils.makePath(parentDef.getEndpoint(attrs, options), attrs[parentKey], thisEndpoint); } else if (item && parentKey in item) { delete options.params[parentKey]; endpoint = DSUtils.makePath(parentDef.getEndpoint(attrs, options), item[parentKey], thisEndpoint); } else if (options && options.params[parentKey]) { endpoint = DSUtils.makePath(parentDef.getEndpoint(attrs, options), options.params[parentKey], thisEndpoint); delete options.params[parentKey]; } } if (options.params[parentKey] === false) { delete options.params[parentKey]; } return endpoint || thisEndpoint; }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource def['class'] = DSUtils.pascalCase(definition.name); try { eval('function ' + def['class'] + '() {}'); def[def['class']] = eval(def['class']); } catch (e) { def[def['class']] = function () { }; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[def['class']].prototype, def.methods); } // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { console.warn('Computed property "' + field + '" conflicts with previously defined prototype method!'); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(','); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { console.warn('Use the computed property array syntax for compatibility with minified code!'); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.name, definition.schema); if (!definition.hasOwnProperty('validate')) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[def['class']].prototype['DS' + DSUtils.pascalCase(name)] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(this[def.idAttribute] || this); args.unshift(def.name); return _this[name].apply(_this, args); }; }); // Initialize store data for the new resource _this.store[def.name] = { collection: [], expiresHeap: new DSUtils.DSBinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { _this.reap(def.name, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones for (var key in _this) { if (typeof _this[key] === 'function' && key !== 'defineResource') { (function (k) { def[k] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(def.name); return _this[k].apply(_this, args); }; })(key); } } def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); // Mix-in events DSUtils.Events(def); return def; } catch (err) { console.error(err); delete definitions[definition.name]; delete _this.store[definition.name]; throw err; } } module.exports = defineResource; },{"../../errors":70,"../../utils":72}],61:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function eject(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var item; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { if (options.notify) { definition.beforeEject(options, item); } _this.unlinkInverse(definition.name, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); _this.emit(definition, 'eject', item); } return item; } } module.exports = eject; },{"../../errors":70,"../../utils":72}],62:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function ejectAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; params = params || {}; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isObject(params)) { throw new DSErrors.IA('"params" must be an object!'); } var resource = _this.store[resourceName]; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.name, params); var ids = DSUtils.toLookup(items, definition.idAttribute); DSUtils.forOwn(ids, function (item, id) { _this.eject(definition.name, id, options); }); delete resource.completedQueries[queryHash]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } module.exports = ejectAll; },{"../../errors":70,"../../utils":72}],63:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function filter(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } else if (params && !DSUtils.isObject(params)) { throw new DSErrors.IA('"params" must be an object!'); } options = DSUtils._(definition, options); // Protect against null params = params || {}; var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } module.exports = filter; },{"../../errors":70,"../../utils":72}],64:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); var NER = DSErrors.NER; var IA = DSErrors.IA; function changes(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); var item = _this.get(resourceName, id); if (item) { if (DSUtils.w) { _this.store[resourceName].observers[id].deliver(); } var diff = DSUtils.diffObjectFromOldObject(item, _this.store[resourceName].previousAttributes[id], options.ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return diff; } } function changeHistory(resourceName, id) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.definitions[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } if (!definition.keepChangeHistory) { console.warn('changeHistory is disabled for this resource!'); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } } function compute(resourceName, instance) { var _this = this; var definition = _this.definitions[resourceName]; instance = DSUtils.resolveItem(_this.store[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isObject(instance) && !DSUtils.isString(instance) && !DSUtils.isNumber(instance)) { throw new IA('"instance" must be an object, string or number!'); } if (DSUtils.isString(instance) || DSUtils.isNumber(instance)) { instance = _this.get(resourceName, instance); } DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field, DSUtils); }); return instance; } function createInstance(resourceName, attrs, options) { var definition = this.definitions[resourceName]; var item; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA('"attrs" must be an object!'); } options = DSUtils._(definition, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition.class]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, attrs); } return item; } function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } function digest() { this.observe.Platform.performMicrotaskCheckpoint(); } function get(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); // cache miss, request resource from server var item = _this.store[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; } function getAll(resourceName, ids) { var _this = this; var resource = _this.store[resourceName]; var collection = []; if (!_this.definitions[resourceName]) { throw new NER(resourceName); } else if (ids && !DSUtils.isArray(ids)) { throw new IA('"ids" must be an array!'); } if (DSUtils.isArray(ids)) { var length = ids.length; for (var i = 0; i < length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; } function hasChanges(resourceName, id) { var _this = this; id = DSUtils.resolveId(_this.definitions[resourceName], id); if (!_this.definitions[resourceName]) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } } function lastModified(resourceName, id) { var definition = this.definitions[resourceName]; var resource = this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; } function lastSaved(resourceName, id) { var definition = this.definitions[resourceName]; var resource = this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; } function previous(resourceName, id) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } // return resource from cache return resource.previousAttributes[id] ? DSUtils.merge({}, resource.previousAttributes[id]) : undefined; } module.exports = { changes: changes, changeHistory: changeHistory, compute: compute, createInstance: createInstance, defineResource: require('./defineResource'), digest: digest, eject: require('./eject'), ejectAll: require('./ejectAll'), filter: require('./filter'), get: get, getAll: getAll, hasChanges: hasChanges, inject: require('./inject'), lastModified: lastModified, lastSaved: lastSaved, link: require('./link'), linkAll: require('./linkAll'), linkInverse: require('./linkInverse'), previous: previous, unlinkInverse: require('./unlinkInverse') }; },{"../../errors":70,"../../utils":72,"./defineResource":60,"./eject":61,"./ejectAll":62,"./filter":63,"./inject":65,"./link":66,"./linkAll":67,"./linkInverse":68,"./unlinkInverse":69}],65:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function _injectRelations(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.definitions[relationName]; if (injected[def.localField]) { if (!relationDef) { throw new DSErrors.R(definition.name + ' relation is defined, but the resource is not!'); } try { injected[def.localField] = _this.inject(relationName, injected[def.localField], options); } catch (err) { console.error(definition.name + ': Failed to inject ' + def.type + ' relation: "' + relationName + '"!', err); } } }); } function _getReactFunction(DS, definition, resource) { var name = definition.name; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item; var innerId = (oldValueFn && oldValueFn(definition.idAttribute)) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field, DSUtils); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { console.error('Doh! You just changed the primary key of an object! Your data for the' + name + '" resource is now in an undefined (probably broken) state.'); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected; if (DSUtils.isArray(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); } if (!(idA in attrs)) { var error = new DSErrors.R(definition.name + '.inject: "attrs" must contain the property specified by `idAttribute`!'); console.error(error); throw error; } else { try { var id = attrs[idA]; var item = _this.get(definition.name, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition['class']]) { item = attrs; } else { item = new definition[definition['class']](); } } else { item = {}; } resource.previousAttributes[id] = {}; DSUtils.deepMixIn(item, attrs); DSUtils.deepMixIn(resource.previousAttributes[id], attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); if (definition.relations) { _injectRelations.call(_this, definition, item, options); } } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = {}; DSUtils.deepMixIn(resource.previousAttributes[id], attrs); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { console.error(err.stack); console.error('inject failed!', definition.name, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === 'belongsTo' && injected[definition.idAttribute]) { _this.link(definition.name, injected[definition.idAttribute], [def.relation]); } else if ((options.findHasMany && def.type === 'hasMany') || (options.findHasOne && def.type === 'hasOne')) { _this.link(definition.name, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var injected; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isObject(attrs) && !DSUtils.isArray(attrs)) { throw new DSErrors.IA(resourceName + '.inject: "attrs" must be an object or an array!'); } var name = definition.name; options = DSUtils._(definition, options); if (options.notify) { options.beforeInject(options, attrs); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils.isArray(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils.isArray(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); _this.emit(options, 'inject', injected); } return injected; } module.exports = inject; },{"../../errors":70,"../../utils":72}],66:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function link(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } var params = {}; if (def.type === 'belongsTo') { var parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (parent) { linked[def.localField] = parent; } } else if (def.type === 'hasMany') { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === 'hasOne') { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } module.exports = link; },{"../../errors":70,"../../utils":72}],67:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkAll(resourceName, params, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } if (def.type === 'belongsTo') { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === 'hasMany') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === 'hasOne') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } module.exports = linkAll; },{"../../errors":70,"../../utils":72}],68:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkInverse(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.definitions, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.name)) { return; } if (definition.name === relationName) { _this.linkAll(d.name, {}, [definition.name]); } }); }); }); } return linked; } module.exports = linkInverse; },{"../../errors":70,"../../utils":72}],69:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function unlinkInverse(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.definitions, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.name === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.store[def.name].collection, function (item) { if (def.type === 'hasMany' && item[def.localField]) { var index; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); item[def.localField].splice(index, 1); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } module.exports = unlinkInverse; },{"../../errors":70,"../../utils":72}],70:[function(require,module,exports){ function IllegalArgumentError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = new Error(); IllegalArgumentError.prototype.constructor = IllegalArgumentError; function RuntimeError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = new Error(); RuntimeError.prototype.constructor = RuntimeError; function NonexistentResourceError(resourceName) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = (resourceName || '') + ' is not a registered resource!'; } NonexistentResourceError.prototype = new Error(); NonexistentResourceError.prototype.constructor = NonexistentResourceError; module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; },{}],71:[function(require,module,exports){ var DS = require('./datastore'); module.exports = { DS: DS, createStore: function (options) { return new DS(options); }, DSUtils: require('./utils'), DSErrors: require('./errors') }; },{"./datastore":59,"./errors":70,"./utils":72}],72:[function(require,module,exports){ (function (global){ var DSErrors = require('./errors'); var isFunction = require('mout/lang/isFunction'); var w; var _Promise; var es6Promise = require('es6-promise'); es6Promise.polyfill(); function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype['finally']) { w.Promise.prototype['finally'] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; if (!global.Promise.prototype['finally']) { global.Promise.prototype['finally'] = finallyPolyfill; } _Promise = global.Promise; } function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { var args = Array.prototype.slice.call(arguments); var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(parent)) { break; } else { heap[parentN] = element; heap[n] = parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ function bubbleDown(heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } } function DSBinaryHeap(weightFunc, compareFunc) { if (weightFunc && !isFunction(weightFunc)) { throw new Error('DSBinaryHeap(weightFunc): weightFunc: must be a function!'); } weightFunc = weightFunc || function (x) { return x; }; compareFunc = compareFunc || function (x, y) { return x === y; }; this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } var dsp = DSBinaryHeap.prototype; dsp.push = function (node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); }; dsp.peek = function () { return this.heap[0]; }; dsp.pop = function () { var front = this.heap[0], end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; }; dsp.remove = function (node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; }; dsp.removeAll = function () { this.heap = []; }; dsp.size = function () { return this.heap.length; }; var toPromisify = [ 'beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy' ]; var find = require('mout/array/find'); var isRegExp = require('mout/lang/isRegExp'); function isBlacklisted(prop, blacklist) { if (!blacklist || !blacklist.length) { return false; } var matches = find(blacklist, function (blItem) { if ((isRegExp(blItem) && blItem.test(prop)) || blItem === prop) { return prop; } }); return !!matches; } module.exports = { w: w, DSBinaryHeap: DSBinaryHeap, isBoolean: require('mout/lang/isBoolean'), isString: require('mout/lang/isString'), isArray: require('mout/lang/isArray'), isObject: require('mout/lang/isObject'), isNumber: require('mout/lang/isNumber'), isFunction: isFunction, isEmpty: require('mout/lang/isEmpty'), isRegExp: isRegExp, toJson: JSON.stringify, fromJson: function (json) { return this.isString(json) ? JSON.parse(json) : json; }, makePath: require('mout/string/makePath'), upperCase: require('mout/string/upperCase'), pascalCase: require('mout/string/pascalCase'), deepMixIn: require('mout/object/deepMixIn'), mixIn: require('mout/object/mixIn'), forOwn: require('mout/object/forOwn'), forEach: require('mout/array/forEach'), pick: require('mout/object/pick'), set: require('mout/object/set'), merge: require('mout/object/merge'), contains: require('mout/array/contains'), filter: require('mout/array/filter'), find: find, toLookup: require('mout/array/toLookup'), remove: require('mout/array/remove'), slice: require('mout/array/slice'), sort: require('mout/array/sort'), // Options that inherit from defaults _: function (parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!_this.isObject(options)) { throw new DSErrors.IA('"options" must be an object!'); } _this.forEach(toPromisify, function (name) { if (typeof options[name] === 'function' && options[name].toString().indexOf('var args = Array') === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { _this.mixIn(this, attrs); }; O.prototype = parent; return new O(options); }, resolveItem: function (resource, idOrInstance) { if (resource && (this.isString(idOrInstance) || this.isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }, resolveId: function (definition, idOrInstance) { if (this.isString(idOrInstance) || this.isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }, updateTimestamp: updateTimestamp, Promise: _Promise, compute: function (fn, field, DSUtils) { var _this = this; var args = []; DSUtils.forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property this[field] = fn[fn.length - 1].apply(this, args); }, diffObjectFromOldObject: function (object, oldObject, blacklist) { var added = {}; var removed = {}; var changed = {}; blacklist = blacklist || []; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, blacklist)) { continue; } if (newValue !== undefined && newValue === oldObject[prop]) { continue; } if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) { changed[prop] = newValue; } } for (var prop2 in object) { if (prop2 in oldObject) { continue; } if (isBlacklisted(prop2, blacklist)) { continue; } added[prop2] = object[prop2]; } return { added: added, removed: removed, changed: changed }; }, promisify: function (fn, target) { var Promise = this.Promise; if (!fn) { return; } else if (typeof fn !== 'function') { throw new Error('Can only promisify functions!'); } return function () { var args = Array.prototype.slice.apply(arguments); return new Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, Events: Events }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./errors":70,"es6-promise":2,"mout/array/contains":4,"mout/array/filter":5,"mout/array/find":6,"mout/array/forEach":8,"mout/array/remove":11,"mout/array/slice":12,"mout/array/sort":13,"mout/array/toLookup":14,"mout/lang/isArray":20,"mout/lang/isBoolean":21,"mout/lang/isEmpty":22,"mout/lang/isFunction":23,"mout/lang/isNumber":25,"mout/lang/isObject":26,"mout/lang/isRegExp":28,"mout/lang/isString":29,"mout/object/deepMixIn":33,"mout/object/forOwn":35,"mout/object/merge":37,"mout/object/mixIn":38,"mout/object/pick":40,"mout/object/set":41,"mout/string/makePath":44,"mout/string/pascalCase":45,"mout/string/upperCase":48}]},{},[71])(71) });
webpack/scenes/RedHatRepositories/components/EnabledRepository/EnabledRepository.js
pmoravec/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ListView } from 'patternfly-react'; import { sprintf, translate as __ } from 'foremanReact/common/I18n'; import RepositoryTypeIcon from '../RepositoryTypeIcon'; import EnabledRepositoryContent from './EnabledRepositoryContent'; class EnabledRepository extends Component { constructor(props) { super(props); this.disableTooltipId = `disable-${props.id}`; } setDisabled = () => { this.props.setRepositoryDisabled(this.repoForAction()); }; repoForAction = () => { const { productId, contentId, arch, releasever, name, type, } = this.props; return { contentId, productId, name, type, arch, releasever, }; }; reload = () => ( this.props.loadEnabledRepos({ ...this.props.pagination, search: this.props.search, }, true) ); notifyDisabled = () => { window.tfm.toastNotifications.notify({ message: sprintf(__("Repository '%(repoName)s' has been disabled."), { repoName: this.props.name }), type: 'success', }); }; reloadAndNotify = async (result) => { if (result && result.success) { await this.reload(); await this.setDisabled(); await this.notifyDisabled(); } }; disableRepository = async () => { const result = await this.props.disableRepository(this.repoForAction()); this.reloadAndNotify(result); }; render() { const { name, id, type, orphaned, label, } = this.props; return ( <ListView.Item key={id} actions={ <EnabledRepositoryContent loading={this.props.loading} disableTooltipId={this.disableTooltipId} disableRepository={this.disableRepository} /> } leftContent={<RepositoryTypeIcon id={id} type={type} />} heading={`${name} ${orphaned ? __('(Orphaned)') : ''}`} description={label} stacked /> ); } } EnabledRepository.propTypes = { id: PropTypes.number.isRequired, contentId: PropTypes.number.isRequired, productId: PropTypes.number.isRequired, label: PropTypes.string.isRequired, name: PropTypes.string.isRequired, type: PropTypes.string.isRequired, arch: PropTypes.string.isRequired, search: PropTypes.shape({ query: PropTypes.string, searchList: PropTypes.string, filters: PropTypes.array, }), pagination: PropTypes.shape({ page: PropTypes.number, perPage: PropTypes.number, }).isRequired, loading: PropTypes.bool, releasever: PropTypes.string, orphaned: PropTypes.bool, setRepositoryDisabled: PropTypes.func.isRequired, loadEnabledRepos: PropTypes.func.isRequired, disableRepository: PropTypes.func.isRequired, }; EnabledRepository.defaultProps = { releasever: '', orphaned: false, search: {}, loading: false, }; export default EnabledRepository;
ajax/libs/styled-components/4.0.0-beta.9-macro/styled-components.min.js
cdnjs/cdnjs
var styled=function(e){"use strict";var t="default"in e?e.default:e;function r(e){return e&&"string"==typeof e.styledComponentId}var n=function(e,t){for(var r=[e[0]],n=0,a=t.length;n<a;n+=1)r.push(t[n],e[n+1]);return r},a="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},o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=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},c=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},l=function(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},u=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},f=function(e){return"object"===(void 0===e?"undefined":a(e))&&e.constructor===Object},d=Object.freeze([]),h=Object.freeze({});function p(e){return"function"==typeof e}var m="undefined"!=typeof process&&process.env.SC_ATTR||"data-styled",y="undefined"!=typeof window&&"HTMLElement"in window,g={},v=function(e){function t(r){o(this,t);for(var n=arguments.length,a=Array(n>1?n-1:0),i=1;i<n;i++)a[i-1]=arguments[i];var s=u(this,e.call(this,"An error occurred. See https://github.com/styled-components/styled-components/blob/master/src/utils/errors.md#"+r+" for more information. "+(a?"Additional arguments: "+a.join(", "):"")));return u(s)}return c(t,e),t}(Error),b=/^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm,k=function(e){var t=""+(e||""),r=[];return t.replace(b,function(e,t,n){return r.push({componentId:t,matchIndex:n}),e}),r.map(function(e,n){var a=e.componentId,o=e.matchIndex,i=r[n+1];return{componentId:a,cssFromDOM:i?t.slice(o,i.matchIndex):t.slice(o)}})};function C(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function w(e,t){return e(t={exports:{}},t.exports),t.exports}var S=w(function(e,t){e.exports=function e(t){var r=/^\0+/g,n=/[\0\r\f]/g,a=/: */g,o=/zoo|gra/,i=/([,: ])(transform)/g,s=/,+\s*(?![^(]*[)])/g,c=/ +\s*(?![^(]*[)])/g,l=/ *[\0] */g,u=/,\r+?/g,f=/([\t\r\n ])*\f?&/g,d=/:global\(((?:[^\(\)\[\]]*|\[.*\]|\([^\(\)]*\))*)\)/g,h=/\W+/g,p=/@(k\w+)\s*(\S*)\s*/,m=/::(place)/g,y=/:(read-only)/g,g=/\s+(?=[{\];=:>])/g,v=/([[}=:>])\s+/g,b=/(\{[^{]+?);(?=\})/g,k=/\s{2,}/g,C=/([^\(])(:+) */g,w=/[svh]\w+-[tblr]{2}/,S=/\(\s*(.*)\s*\)/g,A=/([\s\S]*?);/g,x=/-self|flex-/g,O=/[^]*?(:[rp][el]a[\w-]+)[^]*/,I=/stretch|:\s*\w+\-(?:conte|avail)/,j=/([^-])(image-set\()/,T="-webkit-",R="-moz-",P="-ms-",M=59,E=125,N=123,$=40,F=41,_=91,L=93,H=10,z=13,D=9,U=64,B=32,q=38,V=45,W=95,Y=42,X=44,G=58,Z=39,J=34,K=47,Q=62,ee=43,te=126,re=0,ne=12,ae=11,oe=107,ie=109,se=115,ce=112,le=111,ue=105,fe=99,de=100,he=112,pe=1,me=1,ye=0,ge=1,ve=1,be=1,ke=0,Ce=0,we=0,Se=[],Ae=[],xe=0,Oe=null,Ie=-2,je=-1,Te=0,Re=1,Pe=2,Me=3,Ee=0,Ne=1,$e="",Fe="",_e="";function Le(e,t,a,o,i){for(var s,c,u=0,f=0,d=0,h=0,g=0,v=0,b=0,k=0,w=0,A=0,x=0,O=0,I=0,j=0,W=0,ke=0,Ae=0,Oe=0,Ie=0,je=a.length,ze=je-1,We="",Ye="",Xe="",Ge="",Ze="",Je="";W<je;){if(b=a.charCodeAt(W),W===ze&&f+h+d+u!==0&&(0!==f&&(b=f===K?H:K),h=d=u=0,je++,ze++),f+h+d+u===0){if(W===ze&&(ke>0&&(Ye=Ye.replace(n,"")),Ye.trim().length>0)){switch(b){case B:case D:case M:case z:case H:break;default:Ye+=a.charAt(W)}b=M}if(1===Ae)switch(b){case N:case E:case M:case J:case Z:case $:case F:case X:Ae=0;case D:case z:case H:case B:break;default:for(Ae=0,Ie=W,g=b,W--,b=M;Ie<je;)switch(a.charCodeAt(Ie++)){case H:case z:case M:++W,b=g,Ie=je;break;case G:ke>0&&(++W,b=g);case N:Ie=je}}switch(b){case N:for(g=(Ye=Ye.trim()).charCodeAt(0),x=1,Ie=++W;W<je;){switch(b=a.charCodeAt(W)){case N:x++;break;case E:x--;break;case K:switch(v=a.charCodeAt(W+1)){case Y:case K:W=Ve(v,W,ze,a)}break;case _:b++;case $:b++;case J:case Z:for(;W++<ze&&a.charCodeAt(W)!==b;);}if(0===x)break;W++}switch(Xe=a.substring(Ie,W),g===re&&(g=(Ye=Ye.replace(r,"").trim()).charCodeAt(0)),g){case U:switch(ke>0&&(Ye=Ye.replace(n,"")),v=Ye.charCodeAt(1)){case de:case ie:case se:case V:s=t;break;default:s=Se}if(Ie=(Xe=Le(t,s,Xe,v,i+1)).length,we>0&&0===Ie&&(Ie=Ye.length),xe>0&&(s=He(Se,Ye,Oe),c=qe(Me,Xe,s,t,me,pe,Ie,v,i,o),Ye=s.join(""),void 0!==c&&0===(Ie=(Xe=c.trim()).length)&&(v=0,Xe="")),Ie>0)switch(v){case se:Ye=Ye.replace(S,Be);case de:case ie:case V:Xe=Ye+"{"+Xe+"}";break;case oe:Xe=(Ye=Ye.replace(p,"$1 $2"+(Ne>0?$e:"")))+"{"+Xe+"}",Xe=1===ve||2===ve&&Ue("@"+Xe,3)?"@"+T+Xe+"@"+Xe:"@"+Xe;break;default:Xe=Ye+Xe,o===he&&(Ge+=Xe,Xe="")}else Xe="";break;default:Xe=Le(t,He(t,Ye,Oe),Xe,o,i+1)}Ze+=Xe,O=0,Ae=0,j=0,ke=0,Oe=0,I=0,Ye="",Xe="",b=a.charCodeAt(++W);break;case E:case M:if((Ie=(Ye=(ke>0?Ye.replace(n,""):Ye).trim()).length)>1)switch(0===j&&((g=Ye.charCodeAt(0))===V||g>96&&g<123)&&(Ie=(Ye=Ye.replace(" ",":")).length),xe>0&&void 0!==(c=qe(Re,Ye,t,e,me,pe,Ge.length,o,i,o))&&0===(Ie=(Ye=c.trim()).length)&&(Ye="\0\0"),g=Ye.charCodeAt(0),v=Ye.charCodeAt(1),g){case re:break;case U:if(v===ue||v===fe){Je+=Ye+a.charAt(W);break}default:if(Ye.charCodeAt(Ie-1)===G)break;Ge+=De(Ye,g,v,Ye.charCodeAt(2))}O=0,Ae=0,j=0,ke=0,Oe=0,Ye="",b=a.charCodeAt(++W)}}switch(b){case z:case H:if(f+h+d+u+Ce===0)switch(A){case F:case Z:case J:case U:case te:case Q:case Y:case ee:case K:case V:case G:case X:case M:case N:case E:break;default:j>0&&(Ae=1)}f===K?f=0:ge+O===0&&o!==oe&&Ye.length>0&&(ke=1,Ye+="\0"),xe*Ee>0&&qe(Te,Ye,t,e,me,pe,Ge.length,o,i,o),pe=1,me++;break;case M:case E:if(f+h+d+u===0){pe++;break}default:switch(pe++,We=a.charAt(W),b){case D:case B:if(h+u+f===0)switch(k){case X:case G:case D:case B:We="";break;default:b!==B&&(We=" ")}break;case re:We="\\0";break;case ne:We="\\f";break;case ae:We="\\v";break;case q:h+f+u===0&&ge>0&&(Oe=1,ke=1,We="\f"+We);break;case 108:if(h+f+u+ye===0&&j>0)switch(W-j){case 2:k===ce&&a.charCodeAt(W-3)===G&&(ye=k);case 8:w===le&&(ye=w)}break;case G:h+f+u===0&&(j=W);break;case X:f+d+h+u===0&&(ke=1,We+="\r");break;case J:case Z:0===f&&(h=h===b?0:0===h?b:h);break;case _:h+f+d===0&&u++;break;case L:h+f+d===0&&u--;break;case F:h+f+u===0&&d--;break;case $:if(h+f+u===0){if(0===O)switch(2*k+3*w){case 533:break;default:x=0,O=1}d++}break;case U:f+d+h+u+j+I===0&&(I=1);break;case Y:case K:if(h+u+d>0)break;switch(f){case 0:switch(2*b+3*a.charCodeAt(W+1)){case 235:f=K;break;case 220:Ie=W,f=Y}break;case Y:b===K&&k===Y&&Ie+2!==W&&(33===a.charCodeAt(Ie+2)&&(Ge+=a.substring(Ie,W+1)),We="",f=0)}}if(0===f){if(ge+h+u+I===0&&o!==oe&&b!==M)switch(b){case X:case te:case Q:case ee:case F:case $:if(0===O){switch(k){case D:case B:case H:case z:We+="\0";break;default:We="\0"+We+(b===X?"":"\0")}ke=1}else switch(b){case $:j+7===W&&108===k&&(j=0),O=++x;break;case F:0==(O=--x)&&(ke=1,We+="\0")}break;case D:case B:switch(k){case re:case N:case E:case M:case X:case ne:case D:case B:case H:case z:break;default:0===O&&(ke=1,We+="\0")}}Ye+=We,b!==B&&b!==D&&(A=b)}}w=k,k=b,W++}if(Ie=Ge.length,we>0&&0===Ie&&0===Ze.length&&0===t[0].length==0&&(o!==ie||1===t.length&&(ge>0?Fe:_e)===t[0])&&(Ie=t.join(",").length+2),Ie>0){if(s=0===ge&&o!==oe?function(e){for(var t,r,a=0,o=e.length,i=Array(o);a<o;++a){for(var s=e[a].split(l),c="",u=0,f=0,d=0,h=0,p=s.length;u<p;++u)if(!(0===(f=(r=s[u]).length)&&p>1)){if(d=c.charCodeAt(c.length-1),h=r.charCodeAt(0),t="",0!==u)switch(d){case Y:case te:case Q:case ee:case B:case $:break;default:t=" "}switch(h){case q:r=t+Fe;case te:case Q:case ee:case B:case F:case $:break;case _:r=t+r+Fe;break;case G:switch(2*r.charCodeAt(1)+3*r.charCodeAt(2)){case 530:if(be>0){r=t+r.substring(8,f-1);break}default:(u<1||s[u-1].length<1)&&(r=t+Fe+r)}break;case X:t="";default:r=f>1&&r.indexOf(":")>0?t+r.replace(C,"$1"+Fe+"$2"):t+r+Fe}c+=r}i[a]=c.replace(n,"").trim()}return i}(t):t,xe>0&&void 0!==(c=qe(Pe,Ge,s,e,me,pe,Ie,o,i,o))&&0===(Ge=c).length)return Je+Ge+Ze;if(Ge=s.join(",")+"{"+Ge+"}",ve*ye!=0){switch(2!==ve||Ue(Ge,2)||(ye=0),ye){case le:Ge=Ge.replace(y,":"+R+"$1")+Ge;break;case ce:Ge=Ge.replace(m,"::"+T+"input-$1")+Ge.replace(m,"::"+R+"$1")+Ge.replace(m,":"+P+"input-$1")+Ge}ye=0}}return Je+Ge+Ze}function He(e,t,r){var n=t.trim().split(u),a=n,o=n.length,i=e.length;switch(i){case 0:case 1:for(var s=0,c=0===i?"":e[0]+" ";s<o;++s)a[s]=ze(c,a[s],r,i).trim();break;default:s=0;var l=0;for(a=[];s<o;++s)for(var f=0;f<i;++f)a[l++]=ze(e[f]+" ",n[s],r,i).trim()}return a}function ze(e,t,r,n){var a=t,o=a.charCodeAt(0);switch(o<33&&(o=(a=a.trim()).charCodeAt(0)),o){case q:switch(ge+n){case 0:case 1:if(0===e.trim().length)break;default:return a.replace(f,"$1"+e.trim())}break;case G:switch(a.charCodeAt(1)){case 103:if(be>0&&ge>0)return a.replace(d,"$1").replace(f,"$1"+_e);break;default:return e.trim()+a.replace(f,"$1"+e.trim())}default:if(r*ge>0&&a.indexOf("\f")>0)return a.replace(f,(e.charCodeAt(0)===G?"":"$1")+e.trim())}return e+a}function De(e,t,r,n){var l,u=0,f=e+";",d=2*t+3*r+4*n;if(944===d)return function(e){var t=e.length,r=e.indexOf(":",9)+1,n=e.substring(0,r).trim(),a=e.substring(r,t-1).trim();switch(e.charCodeAt(9)*Ne){case 0:break;case V:if(110!==e.charCodeAt(10))break;default:for(var o=a.split((a="",s)),i=0,r=0,t=o.length;i<t;r=0,++i){for(var l=o[i],u=l.split(c);l=u[r];){var f=l.charCodeAt(0);if(1===Ne&&(f>U&&f<90||f>96&&f<123||f===W||f===V&&l.charCodeAt(1)!==V))switch(isNaN(parseFloat(l))+(-1!==l.indexOf("("))){case 1:switch(l){case"infinite":case"alternate":case"backwards":case"running":case"normal":case"forwards":case"both":case"none":case"linear":case"ease":case"ease-in":case"ease-out":case"ease-in-out":case"paused":case"reverse":case"alternate-reverse":case"inherit":case"initial":case"unset":case"step-start":case"step-end":break;default:l+=$e}}u[r++]=l}a+=(0===i?"":",")+u.join(" ")}}return a=n+a+";",1===ve||2===ve&&Ue(a,1)?T+a+a:a}(f);if(0===ve||2===ve&&!Ue(f,1))return f;switch(d){case 1015:return 97===f.charCodeAt(10)?T+f+f:f;case 951:return 116===f.charCodeAt(3)?T+f+f:f;case 963:return 110===f.charCodeAt(5)?T+f+f:f;case 1009:if(100!==f.charCodeAt(4))break;case 969:case 942:return T+f+f;case 978:return T+f+R+f+f;case 1019:case 983:return T+f+R+f+P+f+f;case 883:return f.charCodeAt(8)===V?T+f+f:f.indexOf("image-set(",11)>0?f.replace(j,"$1"+T+"$2")+f:f;case 932:if(f.charCodeAt(4)===V)switch(f.charCodeAt(5)){case 103:return T+"box-"+f.replace("-grow","")+T+f+P+f.replace("grow","positive")+f;case 115:return T+f+P+f.replace("shrink","negative")+f;case 98:return T+f+P+f.replace("basis","preferred-size")+f}return T+f+P+f+f;case 964:return T+f+P+"flex-"+f+f;case 1023:if(99!==f.charCodeAt(8))break;return l=f.substring(f.indexOf(":",15)).replace("flex-","").replace("space-between","justify"),T+"box-pack"+l+T+f+P+"flex-pack"+l+f;case 1005:return o.test(f)?f.replace(a,":"+T)+f.replace(a,":"+R)+f:f;case 1e3:switch(u=(l=f.substring(13).trim()).indexOf("-")+1,l.charCodeAt(0)+l.charCodeAt(u)){case 226:l=f.replace(w,"tb");break;case 232:l=f.replace(w,"tb-rl");break;case 220:l=f.replace(w,"lr");break;default:return f}return T+f+P+l+f;case 1017:if(-1===f.indexOf("sticky",9))return f;case 975:switch(u=(f=e).length-10,d=(l=(33===f.charCodeAt(u)?f.substring(0,u):f).substring(e.indexOf(":",7)+1).trim()).charCodeAt(0)+(0|l.charCodeAt(7))){case 203:if(l.charCodeAt(8)<111)break;case 115:f=f.replace(l,T+l)+";"+f;break;case 207:case 102:f=f.replace(l,T+(d>102?"inline-":"")+"box")+";"+f.replace(l,T+l)+";"+f.replace(l,P+l+"box")+";"+f}return f+";";case 938:if(f.charCodeAt(5)===V)switch(f.charCodeAt(6)){case 105:return l=f.replace("-items",""),T+f+T+"box-"+l+P+"flex-"+l+f;case 115:return T+f+P+"flex-item-"+f.replace(x,"")+f;default:return T+f+P+"flex-line-pack"+f.replace("align-content","").replace(x,"")+f}break;case 973:case 989:if(f.charCodeAt(3)!==V||122===f.charCodeAt(4))break;case 931:case 953:if(!0===I.test(e))return 115===(l=e.substring(e.indexOf(":")+1)).charCodeAt(0)?De(e.replace("stretch","fill-available"),t,r,n).replace(":fill-available",":stretch"):f.replace(l,T+l)+f.replace(l,R+l.replace("fill-",""))+f;break;case 962:if(f=T+f+(102===f.charCodeAt(5)?P+f:"")+f,r+n===211&&105===f.charCodeAt(13)&&f.indexOf("transform",10)>0)return f.substring(0,f.indexOf(";",27)+1).replace(i,"$1"+T+"$2")+f}return f}function Ue(e,t){var r=e.indexOf(1===t?":":"{"),n=e.substring(0,3!==t?r:10),a=e.substring(r+1,e.length-1);return Oe(2!==t?n:n.replace(O,"$1"),a,t)}function Be(e,t){var r=De(t,t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2));return r!==t+";"?r.replace(A," or ($1)").substring(4):"("+t+")"}function qe(e,t,r,n,a,o,i,s,c,l){for(var u,f=0,d=t;f<xe;++f)switch(u=Ae[f].call(Ye,e,d,r,n,a,o,i,s,c,l)){case void 0:case!1:case!0:case null:break;default:d=u}switch(d){case void 0:case!1:case!0:case null:case t:break;default:return d}}function Ve(e,t,r,n){for(var a=t+1;a<r;++a)switch(n.charCodeAt(a)){case K:if(e===Y&&n.charCodeAt(a-1)===Y&&t+2!==a)return a+1;break;case H:if(e===K)return a+1}return a}function We(e){for(var t in e){var r=e[t];switch(t){case"keyframe":Ne=0|r;break;case"global":be=0|r;break;case"cascade":ge=0|r;break;case"compress":ke=0|r;break;case"semicolon":Ce=0|r;break;case"preserve":we=0|r;break;case"prefix":Oe=null,r?"function"!=typeof r?ve=1:(ve=2,Oe=r):ve=0}}return We}function Ye(t,r){if(void 0!==this&&this.constructor===Ye)return e(t);var a=t,o=a.charCodeAt(0);o<33&&(o=(a=a.trim()).charCodeAt(0)),Ne>0&&($e=a.replace(h,o===_?"":"-")),o=1,1===ge?_e=a:Fe=a;var i,s=[_e];xe>0&&void 0!==(i=qe(je,r,s,s,me,pe,0,0,0,0))&&"string"==typeof i&&(r=i);var c=Le(Se,s,r,0,0);return xe>0&&void 0!==(i=qe(Ie,c,s,s,me,pe,c.length,0,0,0))&&"string"!=typeof(c=i)&&(o=0),$e="",_e="",Fe="",ye=0,me=1,pe=1,ke*o==0?c:c.replace(n,"").replace(g,"").replace(v,"$1").replace(b,"$1").replace(k," ")}return Ye.use=function e(t){switch(t){case void 0:case null:xe=Ae.length=0;break;default:switch(t.constructor){case Array:for(var r=0,n=t.length;r<n;++r)e(t[r]);break;case Function:Ae[xe++]=t;break;case Boolean:Ee=0|!!t}}return e},Ye.set=We,void 0!==t&&We(t),Ye}(null)}),A=w(function(e,t){e.exports=function(e){function t(t){if(t)try{e(t+"}")}catch(e){}}return function(r,n,a,o,i,s,c,l,u,f){switch(r){case 1:if(0===u&&64===n.charCodeAt(0))return e(n+";"),"";break;case 2:if(0===l)return n+"/*|*/";break;case 3:switch(l){case 102:case 112:return e(a[0]+n),"";default:return n+(0===f?"/*|*/":"")}case-2:n.split("/*|*/}").forEach(t)}}}}),x=/^\s*\/\/.*$/gm,O=new S({global:!1,cascade:!0,keyframe:!1,prefix:!1,compress:!1,semicolon:!0}),I=new S({global:!1,cascade:!0,keyframe:!1,prefix:!0,compress:!1,semicolon:!1}),j=[],T=function(e){if(-2===e){var t=j;return j=[],t}},R=A(function(e){j.push(e)});I.use([R,T]),O.use([R,T]);var P=function(e,t,r){var n=e.join("").replace(x,"");return I(r||!t?"":t,t&&r?r+" "+t+" { "+n+" }":n)},M=function(){return"undefined"!=typeof __webpack_nonce__?__webpack_nonce__:null},E=function(e,t,r){r&&((e[t]||(e[t]=Object.create(null)))[r]=!0)},N=function(e,t){e[t]=Object.create(null)},$=function(e){return function(t,r){return void 0!==e[t]&&e[t][r]}},F=function(e){var t="";for(var r in e)t+=Object.keys(e[r]).join(" ")+" ";return t.trim()},_=function(e){if(e.sheet)return e.sheet;for(var t=document.styleSheets.length,r=0;r<t;r+=1){var n=document.styleSheets[r];if(n.ownerNode===e)return n}throw new v(10)},L=function(e,t,r){if(!t)return!1;var n=e.cssRules.length;try{e.insertRule(t,r<=n?r:n)}catch(e){return!1}return!0},H=function(e){return"\n/* sc-component-id: "+e+" */\n"},z=function(e,t){for(var r=0,n=0;n<=t;n+=1)r+=e[n];return r},D=function(e,t){return function(r){var n=M();return"<style "+[n&&'nonce="'+n+'"',m+'="'+F(t)+'"','data-styled-version="4.0.0-beta.9-macro"',r].filter(Boolean).join(" ")+">"+e()+"</style>"}},U=function(e,r){return function(){var n,a=((n={})[m]=F(r),n["data-styled-version"]="4.0.0-beta.9-macro",n),o=M();return o&&(a.nonce=o),t.createElement("style",s({},a,{dangerouslySetInnerHTML:{__html:e()}}))}},B=function(e){return function(){return Object.keys(e)}},q=function e(t,r){var n=void 0===t?Object.create(null):t,a=void 0===r?Object.create(null):r,o=function(e){var t=a[e];return void 0!==t?t:a[e]=[""]},i=function(){var e="";for(var t in a){var r=a[t][0];r&&(e+=H(t)+r)}return e};return{clone:function(){var t=function(e){var t=Object.create(null);for(var r in e)t[r]=s({},e[r]);return t}(n),r=Object.create(null);for(var o in a)r[o]=[a[o][0]];return e(t,r)},css:i,getIds:B(a),hasNameForId:$(n),insertMarker:o,insertRules:function(e,t,r){o(e)[0]+=t.join(" "),E(n,e,r)},removeRules:function(e){var t=a[e];void 0!==t&&(t[0]="",N(n,e))},sealed:!1,styleTag:null,toElement:U(i,n),toHTML:D(i,n)}},V=function(e,t,r,n,a){return y&&!r?function(e,t){var r=Object.create(null),n=Object.create(null),a=[],o=void 0!==t,i=!1,s=function(e){var t=n[e];return void 0!==t?t:(n[e]=a.length,a.push(0),N(r,e),n[e])},c=function(){var t=_(e).cssRules,r="";for(var o in n){r+=H(o);for(var i=n[o],s=z(a,i),c=s-a[i];c<s;c+=1){var l=t[c];void 0!==l&&(r+=l.cssText)}}return r};return{clone:function(){throw new v(5)},css:c,getIds:B(n),hasNameForId:$(r),insertMarker:s,insertRules:function(n,c,l){for(var u=s(n),f=_(e),d=z(a,u),h=0,p=[],m=c.length,y=0;y<m;y+=1){var g=c[y],v=o;v&&-1!==g.indexOf("@import")?p.push(g):L(f,g,d+h)&&(v=!1,h+=1)}o&&p.length>0&&(i=!0,t().insertRules(n+"-import",p)),a[u]+=h,E(r,n,l)},removeRules:function(s){var c=n[s];if(void 0!==c){var l=a[c];!function(e,t,r){for(var n=t-r,a=t;a>n;a-=1)e.deleteRule(a)}(_(e),z(a,c)-1,l),a[c]=0,N(r,s),o&&i&&t().removeRules(s+"-import")}},sealed:!1,styleTag:e,toElement:U(c,r),toHTML:D(c,r)}}(function(e,t,r){var n=document.createElement("style");n.setAttribute(m,""),n.setAttribute("data-styled-version","4.0.0-beta.9-macro");var a=M();if(a&&n.setAttribute("nonce",a),n.appendChild(document.createTextNode("")),e&&!t)e.appendChild(n);else{if(!t||!e||!t.parentNode)throw new v(6);t.parentNode.insertBefore(n,r?t:t.nextSibling)}return n}(e,t,n),a):q()},W=/\s+/,Y=void 0;Y=y?1e3:-1;var X=0,G=void 0,Z=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y?document.head:null,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];o(this,t),this.getImportRuleTag=function(){var t=e.importRuleTag;if(void 0!==t)return t;var r=e.tags[0];return e.importRuleTag=V(e.target,r?r.styleTag:null,e.forceServer,!0)},X+=1,this.id=X,this.forceServer=n,this.target=n?null:r,this.tagMap={},this.deferred={},this.rehydratedNames={},this.ignoreRehydratedNames={},this.tags=[],this.capacity=1,this.clones=[]}return t.prototype.rehydrate=function(){if(!y||this.forceServer)return this;var e=[],t=[],r=!1,n=document.querySelectorAll("style["+m+'][data-styled-version="4.0.0-beta.9-macro"]'),a=n.length;if(0===a)return this;for(var o=0;o<a;o+=1){var i=n[o];r||(r=!!i.getAttribute("data-styled-streamed"));for(var c=(i.getAttribute(m)||"").trim().split(W),l=c.length,u=0;u<l;u+=1){var f=c[u];this.rehydratedNames[f]=!0}t.push.apply(t,k(i.textContent)),e.push(i)}var d=t.length;if(0===d)return this;var h=function(e,t,r,n){var a,o,i=(a=function(){for(var n=0,a=r.length;n<a;n+=1){var o=r[n],i=o.componentId,s=o.cssFromDOM,c=O("",s);e.insertRules(i,c)}for(var l=0,u=t.length;l<u;l+=1){var f=t[l];f.parentNode&&f.parentNode.removeChild(f)}},o=!1,function(){o||(o=!0,a())});return n&&i(),s({},e,{insertMarker:function(t){return i(),e.insertMarker(t)},insertRules:function(t,r,n){return i(),e.insertRules(t,r,n)},removeRules:function(t){return i(),e.removeRules(t)}})}(this.makeTag(null),e,t,r);this.capacity=Math.max(1,Y-d),this.tags.push(h);for(var p=0;p<d;p+=1)this.tagMap[t[p].componentId]=h;return this},t.reset=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];G=new t(void 0,e).rehydrate()},t.prototype.clone=function(){var e=new t(this.target,this.forceServer);return this.clones.push(e),e.tags=this.tags.map(function(t){for(var r=t.getIds(),n=t.clone(),a=0;a<r.length;a+=1)e.tagMap[r[a]]=n;return n}),e.rehydratedNames=s({},this.rehydratedNames),e.deferred=s({},this.deferred),e},t.prototype.sealAllTags=function(){this.capacity=1,this.tags.forEach(function(e){e.sealed=!0})},t.prototype.makeTag=function(e){var t=e?e.styleTag:null;return V(this.target,t,this.forceServer,!1,this.getImportRuleTag)},t.prototype.getTagForId=function(e){var t=this.tagMap[e];if(void 0!==t&&!t.sealed)return t;var r=this.tags[this.tags.length-1];return this.capacity-=1,0===this.capacity&&(this.capacity=Y,r=this.makeTag(r),this.tags.push(r)),this.tagMap[e]=r},t.prototype.hasId=function(e){return void 0!==this.tagMap[e]},t.prototype.hasNameForId=function(e,t){if(void 0===this.ignoreRehydratedNames[e]&&this.rehydratedNames[t])return!0;var r=this.tagMap[e];return void 0!==r&&r.hasNameForId(e,t)},t.prototype.deferredInject=function(e,t){if(void 0===this.tagMap[e]){for(var r=this.clones,n=0;n<r.length;n+=1)r[n].deferredInject(e,t);this.getTagForId(e).insertMarker(e),this.deferred[e]=t}},t.prototype.inject=function(e,t,r){for(var n=this.clones,a=0;a<n.length;a+=1)n[a].inject(e,t,r);var o=this.getTagForId(e);if(void 0!==this.deferred[e]){var i=this.deferred[e].concat(t);o.insertRules(e,i,r),this.deferred[e]=void 0}else o.insertRules(e,t,r)},t.prototype.remove=function(e){var t=this.tagMap[e];if(void 0!==t){for(var r=this.clones,n=0;n<r.length;n+=1)r[n].remove(e);t.removeRules(e),this.ignoreRehydratedNames[e]=!0,this.deferred[e]=void 0}},t.prototype.toHTML=function(){return this.tags.map(function(e){return e.toHTML()}).join("")},t.prototype.toReactElements=function(){var t=this.id;return this.tags.map(function(r,n){var a="sc-"+t+"-"+n;return e.cloneElement(r.toElement(),{key:a})})},i(t,null,[{key:"master",get:function(){return G||(G=(new t).rehydrate())}},{key:"instance",get:function(){return t.master}}]),t}(),J=function(){function e(t,r){var n=this;o(this,e),this.inject=function(e){e.hasNameForId(n.id,n.name)||e.inject(n.id,n.rules,n.name)},this.name=t,this.rules=r,this.id="sc-keyframes-"+t}return e.prototype.getName=function(){return this.name},e}(),K=/([A-Z])/g,Q=/^ms-/;var ee=function e(t,r){var n=Object.keys(t).filter(function(e){var r=t[e];return null!=r&&!1!==r&&""!==r}).map(function(r){return f(t[r])?e(t[r],r):r.replace(K,"-$1").toLowerCase().replace(Q,"-ms-")+": "+t[r]+";"}).join(" ");return r?r+" {\n "+n+"\n}":n},te=function(e){return null==e||!1===e||""===e};function re(e,t,n){if(Array.isArray(e)){for(var a,o=[],i=0,s=e.length;i<s;i+=1)null!==(a=re(e[i],t,n))&&(Array.isArray(a)?o.push.apply(o,a):o.push(a));return o}return te(e)?null:r(e)?"."+e.styledComponentId:p(e)?t?re(e(t),t,n):e:e instanceof J?n?(e.inject(n),e.getName()):e:f(e)?ee(e):e.toString()}function ne(e){for(var t=arguments.length,r=Array(t>1?t-1:0),a=1;a<t;a++)r[a-1]=arguments[a];return p(e)||f(e)?re(n(d,[e].concat(r))):re(n(e,r))}function ae(e,t){for(var n=0;n<e.length;n+=1){var a=e[n];if(Array.isArray(a)&&!ae(a))return!1;if(p(a)&&!r(a))return!1}if(void 0!==t)for(var o in t){if(p(t[o]))return!1}return!0}var oe=function(){function e(t,r){o(this,e),this.rules=t,this.componentId=r,this.isStatic=ae(t),Z.master.hasId(r)||Z.master.deferredInject(r,[])}return e.prototype.createStyles=function(e,t){var r=re(this.rules,e,t),n=P(r,"");t.inject(this.componentId,n)},e.prototype.removeStyles=function(e){var t=this.componentId;e.hasId(t)&&e.remove(t)},e.prototype.renderStyles=function(e,t){this.removeStyles(t),this.createStyles(e,t)},e}(),ie=function(e,t){return e===t};function se(e,t){var r;void 0===t&&(t=ie);var n,a=[],o=!1,i=function(e,r){return t(e,a[r])};return function(){for(var t=arguments.length,s=new Array(t),c=0;c<t;c++)s[c]=arguments[c];return o&&r===this&&s.length===a.length&&s.every(i)?n:(n=e.apply(this,s),o=!0,r=this,a=s,n)}}var ce=function(){function e(){o(this,e),this.masterSheet=Z.master,this.instance=this.masterSheet.clone(),this.sealed=!1}return e.prototype.seal=function(){if(!this.sealed){var e=this.masterSheet.clones.indexOf(this.instance);this.masterSheet.clones.splice(e,1),this.sealed=!0}},e.prototype.collectStyles=function(e){if(this.sealed)throw new v(2);return t.createElement(fe,{sheet:this.instance},e)},e.prototype.getStyleTags=function(){return this.seal(),this.instance.toHTML()},e.prototype.getStyleElement=function(){return this.seal(),this.instance.toReactElements()},e.prototype.interleaveWithNodeStream=function(e){throw new v(3)},e}(),le=e.createContext(),ue=le.Consumer,fe=function(e){function r(t){o(this,r);var n=u(this,e.call(this,t));return n.getContext=se(n.getContext),n}return c(r,e),r.prototype.getContext=function(e,t){if(e)return e;if(t)return new Z(t);throw new v(4)},r.prototype.render=function(){var e=this.props,r=e.children,n=e.sheet,a=e.target,o=this.getContext(n,a);return t.createElement(le.Provider,{value:o},t.Children.only(r))},r}(e.Component),de=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h,n=!!r&&e.theme===r.theme;return e.theme&&!n?e.theme:t||r.theme},he=e.createContext(),pe=he.Consumer,me=function(e){function r(t){o(this,r);var n=u(this,e.call(this,t));return n.getContext=se(n.getContext.bind(n)),n.renderInner=n.renderInner.bind(n),n}return c(r,e),r.prototype.render=function(){return this.props.children?t.createElement(he.Consumer,null,this.renderInner):null},r.prototype.renderInner=function(e){var r=this.getContext(this.props.theme,e);return t.createElement(he.Provider,{value:r},t.Children.only(this.props.children))},r.prototype.getTheme=function(e,t){if(p(e))return e(t);if(null===e||Array.isArray(e)||"object"!==(void 0===e?"undefined":a(e)))throw new v(8);return s({},t,e)},r.prototype.getContext=function(e,t){return this.getTheme(e,t)},r}(e.Component);function ye(e){for(var t,r=0|e.length,n=0|r,a=0;r>=4;)t=1540483477*(65535&(t=255&e.charCodeAt(a)|(255&e.charCodeAt(++a))<<8|(255&e.charCodeAt(++a))<<16|(255&e.charCodeAt(++a))<<24))+((1540483477*(t>>>16)&65535)<<16),n=1540483477*(65535&n)+((1540483477*(n>>>16)&65535)<<16)^(t=1540483477*(65535&(t^=t>>>24))+((1540483477*(t>>>16)&65535)<<16)),r-=4,++a;switch(r){case 3:n^=(255&e.charCodeAt(a+2))<<16;case 2:n^=(255&e.charCodeAt(a+1))<<8;case 1:n=1540483477*(65535&(n^=255&e.charCodeAt(a)))+((1540483477*(n>>>16)&65535)<<16)}return((n=1540483477*(65535&(n^=n>>>13))+((1540483477*(n>>>16)&65535)<<16))^n>>>15)>>>0}var ge=52,ve=function(e){return String.fromCharCode(e+(e>25?39:97))};function be(e){var t="",r=void 0;for(r=e;r>ge;r=Math.floor(r/ge))t=ve(r%ge)+t;return ve(r%ge)+t}var ke=function(e){return e.replace(/\s|\\n/g,"")};function Ce(e){return e.displayName||e.name||"Component"}var we=w(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&Symbol.for,n=r?Symbol.for("react.element"):60103,a=r?Symbol.for("react.portal"):60106,o=r?Symbol.for("react.fragment"):60107,i=r?Symbol.for("react.strict_mode"):60108,s=r?Symbol.for("react.profiler"):60114,c=r?Symbol.for("react.provider"):60109,l=r?Symbol.for("react.context"):60110,u=r?Symbol.for("react.async_mode"):60111,f=r?Symbol.for("react.forward_ref"):60112,d=r?Symbol.for("react.placeholder"):60113;function h(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case n:switch(e=e.type){case u:case o:case s:case i:return e;default:switch(e=e&&e.$$typeof){case l:case f:case c:return e;default:return t}}case a:return t}}}t.typeOf=h,t.AsyncMode=u,t.ContextConsumer=l,t.ContextProvider=c,t.Element=n,t.ForwardRef=f,t.Fragment=o,t.Profiler=s,t.Portal=a,t.StrictMode=i,t.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===o||e===u||e===s||e===i||e===d||"object"==typeof e&&null!==e&&("function"==typeof e.then||e.$$typeof===c||e.$$typeof===l||e.$$typeof===f)},t.isAsyncMode=function(e){return h(e)===u},t.isContextConsumer=function(e){return h(e)===l},t.isContextProvider=function(e){return h(e)===c},t.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===n},t.isForwardRef=function(e){return h(e)===f},t.isFragment=function(e){return h(e)===o},t.isProfiler=function(e){return h(e)===s},t.isPortal=function(e){return h(e)===a},t.isStrictMode=function(e){return h(e)===i}});C(we);we.typeOf,we.AsyncMode,we.ContextConsumer,we.ContextProvider,we.Element,we.ForwardRef,we.Fragment,we.Profiler,we.Portal,we.StrictMode,we.isValidElementType,we.isAsyncMode,we.isContextConsumer,we.isContextProvider,we.isElement,we.isForwardRef,we.isFragment,we.isProfiler,we.isPortal,we.isStrictMode;var Se=w(function(e,t){});C(Se);Se.typeOf,Se.AsyncMode,Se.ContextConsumer,Se.ContextProvider,Se.Element,Se.ForwardRef,Se.Fragment,Se.Profiler,Se.Portal,Se.StrictMode,Se.isValidElementType,Se.isAsyncMode,Se.isContextConsumer,Se.isContextProvider,Se.isElement,Se.isForwardRef,Se.isFragment,Se.isProfiler,Se.isPortal,Se.isStrictMode;var Ae,xe=w(function(e){e.exports=we}),Oe=xe.isValidElementType,Ie=xe.ForwardRef,je={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDerivedStateFromProps:!0,propTypes:!0,type:!0},Te={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Re=((Ae={})[Ie]={$$typeof:!0,render:!0},Ae),Pe=Object.defineProperty,Me=Object.getOwnPropertyNames,Ee=Object.getOwnPropertySymbols,Ne=void 0===Ee?function(){return[]}:Ee,$e=Object.getOwnPropertyDescriptor,Fe=Object.getPrototypeOf,_e=Object.prototype,Le=Array.prototype;function He(e,t,r){if("string"!=typeof t){var n=Fe(t);n&&n!==_e&&He(e,n,r);for(var a=Le.concat(Me(t),Ne(t)),o=Re[e.$$typeof]||je,i=Re[t.$$typeof]||je,s=a.length,c=void 0,l=void 0;s--;)if(l=a[s],!(Te[l]||r&&r[l]||i&&i[l]||o&&o[l])&&(c=$e(t,l)))try{Pe(e,l,c)}catch(e){}return e}return e}var ze={StyleSheet:Z},De=Object.freeze({css:ne,keyframes:function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var a=ne.apply(void 0,[e].concat(r)),o=be(ye(ke(JSON.stringify(a))));return new J(o,P(a,o,"@keyframes"))},createGlobalStyle:function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),a=1;a<r;a++)n[a-1]=arguments[a];var i=ne.apply(void 0,[e].concat(n)),l="sc-global-"+ye(JSON.stringify(i)),f=new oe(i,l),d=0,h=function(e){function r(){o(this,r);var t=u(this,e.call(this));return d+=1,t.state={globalStyle:t.constructor.globalStyle,styledComponentId:t.constructor.styledComponentId},t}return c(r,e),r.prototype.componentDidMount=function(){},r.prototype.componentWillUnmount=function(){0==(d-=1)&&this.state.globalStyle.removeStyles(this.styleSheet)},r.prototype.render=function(){var e=this;return t.createElement(ue,null,function(r){e.styleSheet=r||Z.master;var n=e.state.globalStyle;return n.isStatic?(n.renderStyles(g,e.styleSheet),null):t.createElement(pe,null,function(t){var r=e.constructor.defaultProps,a=s({},e.props);return void 0!==t&&(a.theme=de(e.props,t,r)),n.renderStyles(a,e.styleSheet),null})})},r}(t.Component);return h.globalStyle=f,h.styledComponentId=l,h},isStyledComponent:r,ThemeConsumer:pe,ThemeProvider:me,withTheme:function(e){var r=t.forwardRef(function(r,n){return t.createElement(pe,null,function(a){var o=e.defaultProps,i=de(r,a,o);return t.createElement(e,s({},r,{theme:i,ref:n}))})});return He(r,e),r.displayName="WithTheme("+Ce(e)+")",r},ServerStyleSheet:ce,StyleSheetManager:fe,__DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS:ze});var Ue,Be,qe=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|default|defer|dir|disabled|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|itemProp|itemScope|itemType|itemID|itemRef|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class)|(on[A-Z].*)|((data|aria|x)-.*))$/i,Ve=(Ue=qe.test.bind(qe),Be={},function(e){return void 0===Be[e]&&(Be[e]=Ue(e)),Be[e]}),We=function(e){return be(ye(e))},Ye=function(){function e(t,r,n){if(o(this,e),this.rules=t,this.isStatic=ae(t,r),this.componentId=n,!Z.master.hasId(n)){Z.master.deferredInject(n,[])}}return e.prototype.generateAndInjectStyles=function(e,t){var r=this.isStatic,n=this.componentId,a=this.lastClassName;if(y&&r&&void 0!==a&&t.hasNameForId(n,a))return a;var o=re(this.rules,e,t),i=We(this.componentId+o.join(""));return t.hasNameForId(n,i)||t.inject(this.componentId,P(o,"."+i),i),this.lastClassName=i,i},e.generateName=function(e){return We(e)},e}(),Xe=/[[\].#*$><+~=|^:(),"'`-]+/g,Ge=/(^-|-$)/g;function Ze(e){return e.replace(Xe,"-").replace(Ge,"")}function Je(e){return"string"==typeof e}var Ke={};var Qe=function(n){function a(){o(this,a);var e=u(this,n.call(this));return e.attrs={},e.renderOuter=e.renderOuter.bind(e),e.renderInner=e.renderInner.bind(e),e}return c(a,n),a.prototype.render=function(){return t.createElement(ue,null,this.renderOuter)},a.prototype.renderOuter=function(e){return this.styleSheet=e,t.createElement(pe,null,this.renderInner)},a.prototype.renderInner=function(t){var r=this.props.forwardedClass,n=r.componentStyle,a=r.defaultProps,o=r.styledComponentId,i=r.target,c=Je(this.props.as||i),l=void 0;l=n.isStatic?this.generateAndInjectStyles(h,this.props,this.styleSheet):void 0!==t?this.generateAndInjectStyles(de(this.props,t,a),this.props,this.styleSheet):this.generateAndInjectStyles(this.props.theme||h,this.props,this.styleSheet);var u=s({},this.attrs),f=void 0;for(f in this.props)"forwardedClass"!==f&&"as"!==f&&("forwardedRef"===f?u.ref=this.props[f]:c&&!Ve(f)||(u[f]="style"===f&&f in this.attrs?s({},this.attrs[f],this.props[f]):this.props[f]));return u.className=[this.props.className,o,this.attrs.className,l].filter(Boolean).join(" "),e.createElement(this.props.as||i,u)},a.prototype.buildExecutionContext=function(e,t,n){var a=s({},t,{theme:e});if(void 0===n)return a;this.attrs={};var o,i=void 0,c=void 0;for(c in n)i=n[c],this.attrs[c]=!p(i)||(o=i)&&o.prototype&&o.prototype.isReactComponent||r(i)?i:i(a);return s({},a,this.attrs)},a.prototype.generateAndInjectStyles=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Z.master,n=t.forwardedClass,a=n.attrs,o=n.componentStyle,i=n.warnTooManyClasses;if(o.isStatic&&void 0===a)return o.generateAndInjectStyles(h,r);var s=o.generateAndInjectStyles(this.buildExecutionContext(e,t,t.forwardedClass.attrs),r);return i&&i(s),s},a}(e.PureComponent);function et(e,n,a){var o=r(e),i=!Je(e),c=n.displayName,u=void 0===c?function(e){return Je(e)?"styled."+e:"Styled("+Ce(e)+")"}(e):c,f=n.componentId,d=void 0===f?function(e,t,r){var n="string"!=typeof t?"sc":Ze(t),a=(Ke[n]||0)+1;Ke[n]=a;var o=n+"-"+e.generateName(n+a);return r?r+"-"+o:o}(Ye,n.displayName,n.parentComponentId):f,h=n.ParentComponent,p=void 0===h?Qe:h,m=n.attrs,y=n.displayName&&n.componentId?Ze(n.displayName)+"-"+n.componentId:n.componentId||d,g=o&&e.attrs?s({},e.attrs,m):m,v=new Ye(o?e.componentStyle.rules.concat(a):a,g,y),b=t.forwardRef(function(e,r){return t.createElement(p,s({},e,{forwardedClass:b,forwardedRef:r}))});return b.attrs=g,b.componentStyle=v,b.displayName=u,b.styledComponentId=y,b.target=o?e.target:e,b.withComponent=function(e){var t=n.componentId,r=l(n,["componentId"]),o=t&&t+"-"+(Je(e)?e:Ze(Ce(e)));return et(e,s({},r,{attrs:g,componentId:o,ParentComponent:p}),a)},i&&He(b,e,{attrs:!0,componentStyle:!0,displayName:!0,styledComponentId:!0,target:!0,warnTooManyClasses:!0,withComponent:!0}),b}var tt=function(e){return function e(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h;if(!Oe(r))throw new v(1,String(r));var a=function(){return t(r,n,ne.apply(void 0,arguments))};return a.withConfig=function(a){return e(t,r,s({},n,a))},a.attrs=function(a){return e(t,r,s({},n,{attrs:s({},n.attrs||h,a)}))},a}(et,e)};for(var rt in["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"].forEach(function(e){tt[e]=tt(e)}),De)tt[rt]=De[rt];return tt}(React);window.styled=styled; //# sourceMappingURL=styled-components.min.js.map
src/encoded/static/components/collection.js
ENCODE-DCC/encoded
import React from 'react'; import PropTypes from 'prop-types'; import { Panel, PanelHeading, PanelBody } from '../libs/ui/panel'; import * as globals from './globals'; import DataColors from './datacolors'; import { ItemAccessories, controlTypeParameter } from './objectutils'; // Maximum number of facet charts to display. const MAX_FACET_CHARTS = 3; // Initialize a list of colors to use in the chart. const collectionColors = new DataColors(); // Get a list of colors to use for the lab chart const collectionColorList = collectionColors.colorList(); const getControlType = (link) => { if (!link) { return ''; } const type = link.replace('/search/?type=', ''); return controlTypeParameter(type); }; class FacetChart extends React.Component { constructor() { super(); this.chartInstance = null; } componentDidUpdate() { // This method might be called because we're drawing the chart for the first time (in // that case this is an update because we already rendered an empty canvas before the // chart.js module was loaded) or because we have new data to render into an existing // chart. const { chartId, facet, baseSearchUri } = this.props; const Chart = this.props.chartModule; // Before rendering anything into the chart, check whether we have a the chart.js module // loaded yet. If it hasn't loaded yet, we have nothing to do yet. Also see if we have any // values to render at all, and skip this if not. if (Chart && this.values.length > 0) { // In case we don't have enough colors defined for all the values, make an array of // colors with enough entries to fill out the labels and values. const colors = this.labels.map((label, i) => collectionColorList[i % collectionColorList.length]); if (this.chartInstance) { // We've already created a chart instance, so just update it with new data. this.chartInstance.data.datasets[0].data = this.values; this.chartInstance.data.datasets[0].backgroundColor = colors; this.chartInstance.data.labels = this.labels; this.chartInstance.update(); document.getElementById(`${chartId}-legend`).innerHTML = this.chartInstance.generateLegend(); } else { // We've not yet created a chart instance, so make a new one with the initial set // of data. First extract the data in a way suitable for the chart API. const canvas = document.getElementById(chartId); const ctx = canvas.getContext('2d'); // Create and render the chart. this.chartInstance = new Chart(ctx, { type: 'doughnut', data: { labels: this.labels, datasets: [{ data: this.values, backgroundColor: colors, }], }, options: { maintainAspectRatio: false, responsive: true, legend: { display: false, }, animation: { duration: 200, }, legendCallback: (chart) => { const chartData = chart.data.datasets[0].data; const chartColors = chart.data.datasets[0].backgroundColor; const chartLabels = chart.data.labels; const text = []; text.push('<ul>'); for (let i = 0; i < chartData.length; i += 1) { const searchUri = `${baseSearchUri}${getControlType(baseSearchUri)}&${facet.field}=${encodeURIComponent(chartLabels[i]).replace(/%20/g, '+')}`; if (chartData[i]) { text.push(`<li><a href="${searchUri}">`); text.push(`<i class="icon icon-circle chart-legend-chip" aria-hidden="true" style="color:${chartColors[i]}"></i>`); text.push(`<span class="chart-legend-label">${chartLabels[i]}</span>`); text.push('</a></li>'); } } text.push('</ul>'); return text.join(''); }, onClick: (e) => { // React to clicks on pie sections const activePoints = this.chartInstance.getElementAtEvent(e); if (activePoints[0]) { const clickedElementIndex = activePoints[0]._index; const chartLabels = this.chartInstance.data.labels; const searchUri = `${baseSearchUri}${getControlType(baseSearchUri)}&${facet.field}=${encodeURIComponent(chartLabels[clickedElementIndex]).replace(/%20/g, '+')}`; this.context.navigate(searchUri); } }, }, }); // Create and render the legend by drawing it into the <div> we set up for that // purpose. document.getElementById(`${chartId}-legend`).innerHTML = this.chartInstance.generateLegend(); } } } render() { const { chartId, facet } = this.props; // Extract the arrays of labels from the facet keys, and the arrays of corresponding counts // from the facet doc_counts. Only use non-zero facet terms in the charts. IF we have no // usable data, both these arrays have no entries. componentDidMount assumes these arrays // have been populated. this.values = []; this.labels = []; facet.terms.forEach((term) => { if (term.doc_count) { this.values.push(term.doc_count); this.labels.push(term.key); } }); // Check whether we have usable values in one array or the other we just collected (we'll // just use `this;values` here) to see if we need to render a chart or not. if (this.values.length > 0) { return ( <div className="collection-charts__chart"> <div className="collection-charts__title">{facet.title}</div> <div className="collection-charts__canvas"> <canvas id={chartId} /> </div> <div id={`${chartId}-legend`} className="collection-charts__legend" /> </div> ); } return null; } } FacetChart.propTypes = { facet: PropTypes.object.isRequired, // Facet data to display in the chart chartId: PropTypes.string.isRequired, // HTML element ID to assign to the chart <canvas> chartModule: PropTypes.func, // chart.js NPM module as loaded by webpack baseSearchUri: PropTypes.string.isRequired, // Base URL of clicked chart elements }; FacetChart.defaultProps = { chartModule: null, }; FacetChart.contextTypes = { navigate: PropTypes.func, }; class Collection extends React.Component { constructor() { super(); // Initialize component React state. this.state = { chartModule: null, // Refers to chart.js npm module }; } componentDidMount() { // Have webpack load the chart.js npm module. Once the module's ready, set the chartModule // state so we can redraw the charts with the chart module in place. require.ensure(['chart.js'], (require) => { const Chart = require('chart.js'); this.setState({ chartModule: Chart }); }); } render() { const { context } = this.props; const { facets } = context; // Collect the three facets that will be included in the charts. This comprises the first // MAX_FACET_CHARTS facets, not counting any facets with "type" for the field which we never // chart, nor audit facets. const chartFacets = facets ? facets.filter((facet) => facet.field !== 'type' && facet.field.substring(0, 6) !== 'audit.').slice(0, MAX_FACET_CHARTS) : []; return ( <div className={globals.itemClass(context, 'view-item')}> <header> <h1>{context.title}</h1> {context.schema_description ? <h4 className="collection-sub-header">{context.schema_description}</h4> : null} <ItemAccessories item={context} /> </header> <Panel> <PanelHeading addClasses="collection-heading"> <h4>{context.total} total {context.title}</h4> <div className="collection-heading__controls"> {(context.actions || []).map((action) => ( <a key={action.name} href={action.href} className="btn btn-info"> {action.title} </a> ))} </div> </PanelHeading> <PanelBody> {chartFacets.length > 0 ? <div className="collection-charts"> {chartFacets.map((facet) => ( <FacetChart key={facet.field} facet={facet} chartId={`${facet.field}-chart`} chartModule={this.state.chartModule} baseSearchUri={context.clear_filters} /> ))} </div> : <p className="collection-no-chart">No facets defined in the &ldquo;{context.title}&rdquo; schema, or no data available.</p> } </PanelBody> </Panel> </div> ); } } Collection.propTypes = { context: PropTypes.object.isRequired, }; globals.contentViews.register(Collection, 'Collection');
src/Svg/LinkToReferece.js
numieco/patriot-trading
import React from 'react' const LinkToReferece = () => { return ( <div> <svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink"> <title>Group 5 Copy 2</title> <desc>Created with Sketch.</desc> <defs></defs> <g id="Welcome" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd"> <g id="Tablet" transform="translate(-425.000000, -1127.000000)"> <g id="Group-5-Copy-2" transform="translate(425.000000, 1127.000000)"> <circle id="Oval-2" fill="#272829" cx="10" cy="10" r="10"></circle> <g id="Group" transform="translate(4.666667, 4.666667)" fillRule="nonzero" fill="#FFFFFF"> <g id="link"> <path d="M7.10015405,3.55485714 C7.32217795,3.776 7.49979283,4.04137566 7.63301992,4.30675132 C8.12147676,5.324 7.96604515,6.60662434 7.10015405,7.44696296 L4.72450465,9.83530159 C3.63658964,10.9188995 1.88260292,10.9188995 0.81689243,9.83530159 C-0.271022576,8.7517037 -0.271022576,7.00467725 0.81689243,5.94319577 L2.5042656,4.26251852 C2.30444622,4.92594709 2.32665073,5.63360847 2.57087915,6.27492063 L1.86039841,6.98258201 C1.37194157,7.46910053 1.37194157,8.28732275 1.86039841,8.79595767 C2.37105976,9.30459259 3.17033732,9.30459259 3.68099867,8.79595767 L6.05664807,6.42973545 C6.30087649,6.18647619 6.43408234,5.85477249 6.43408234,5.52304762 C6.43408234,5.19132275 6.30087649,4.85961905 6.05664807,4.61635979 C5.81241965,4.37310053 5.47939442,4.24042328 5.14634794,4.24042328 L6.34526428,3.04626455 C6.61169721,3.15680423 6.85592563,3.33371429 7.10015405,3.55485714 Z" id="Shape"></path> <path d="M3.54777158,7.09314286 C3.32574768,6.872 3.1481328,6.60662434 3.01490571,6.34124868 C2.52644887,5.324 2.68188048,4.04137566 3.54777158,3.20101587 L5.92342098,0.812698413 C7.01133599,-0.270899471 8.76532271,-0.270899471 9.8310332,0.812698413 C10.9189482,1.8962963 10.9189482,3.64332275 9.8310332,4.70480423 L8.14366003,6.38548148 C8.34347942,5.72205291 8.3212749,5.01439153 8.07704648,4.37307937 L8.78752722,3.66541799 C9.27598406,3.17889947 9.27598406,2.36067725 8.78752722,1.85204233 C8.27686587,1.34340741 7.47758831,1.34340741 6.96692696,1.85204233 L4.61348207,4.24040212 C4.36925365,4.48366138 4.23604781,4.81536508 4.23604781,5.14708995 C4.23604781,5.47881481 4.36925365,5.81051852 4.61348207,6.05377778 C4.85771049,6.29703704 5.19073572,6.42971429 5.5237822,6.42971429 L4.32486587,7.62387302 C4.03622842,7.49119577 3.792,7.31428571 3.54777158,7.09314286 Z" id="Shape"></path> </g> </g> </g> </g> </g> </svg> </div> ) } export default LinkToReferece
definitions/npm/formik_v2.x.x/flow_v0.69.0-v0.103.x/test_formik.js
splodingsocks/FlowTyped
// @flow import React from 'react'; import { it, describe } from 'flow-typed-test'; import { Form, getActiveElement, getIn, setIn, setNestedObjectValues, ErrorMessage, FormikProvider, FormikConsumer, useFormikContext, Field, FastField, isFunction, isObject, isInteger, isString, isNaN, isEmptyChildren, isPromise, isInputEvent, useField, withFormik, move, swap, insert, replace, FieldArray, useFormik, Formik, type InjectedFormikProps, } from 'formik'; describe('withFormik HOC', () => { type FormValues = {| age: number, name: string, birthday: Date |}; describe('wrapped component props', () => { type FormOwnProps = {| onSubmit: FormValues => void, variant: 'active' | 'passive', |}; const MyForm = (props: InjectedFormikProps<FormOwnProps, FormValues>) => null; const WithFormikForm = withFormik<FormOwnProps, FormValues>({ handleSubmit(values, { props: { onSubmit }, setSubmitting }) { onSubmit(values); setSubmitting(false); }, })(MyForm); it('should work when pass valid own props', () => { <WithFormikForm variant={'active'} onSubmit={(v: FormValues) => {}} />; }); it('should raise an error when pass invalid own props', () => { <WithFormikForm // $FlowExpectedError[incompatible-type] -`__active` is missing in enum variant={'__active'} onSubmit={(v: FormValues) => {}} />; <WithFormikForm variant={'passive'} // $FlowExpectedError[incompatible-type] - need function onSubmit={123} />; }); it('should raise an error when pass injected formik props', () => { // $FlowExpectedError[prop-missing] - isSubmitting was extracted <WithFormikForm isSubmitting={false} variant={'active'} onSubmit={(v: FormValues) => {}} />; }); }); describe('HOC config', () => { type Props = {| initialName: string, initialAge: number, initialBirthday: Date, |}; const requiredOptions = { handleSubmit: () => {} }; describe('handleSubmit', () => { it('should pass when use properly', () => { withFormik<Props, FormValues>({ handleSubmit(values, { props }) { (values.age: number); (props.initialName: string); // $FlowExpectedError[incompatible-cast] - check any (values.age: boolean); // $FlowExpectedError[incompatible-cast] - check any (props.initialName: boolean); }, }); }); }); describe('handleSubmit', () => { it('should pass when use properly', () => { withFormik<Props, FormValues>({ ...requiredOptions, mapPropsToValues: ({ initialAge }) => ({ age: initialAge }), }); }); it('should raise an error when `mapPropsToValues` return invalid values', () => { withFormik<Props, FormValues>({ ...requiredOptions, // $FlowExpectedError[incompatible-call] - `initialAge` is a number but `name` need a string mapPropsToValues: ({ initialAge }) => ({ name: initialAge, }), }); }); it('should raise an error when `mapPropsToValues` return not missing value', () => { withFormik<Props, FormValues>({ ...requiredOptions, // $FlowExpectedError[prop-missing] - `abc` is missing in values mapPropsToValues: ({ initialAge }) => ({ abc: initialAge, }), }); }); it('should return partial of values', () => { withFormik<Props, { name: string, age: number, ... }>({ ...requiredOptions, mapPropsToValues: ({ initialAge }) => ({ age: initialAge, }), }); }); }); }); }); describe('useField hook', () => { it('should call with string', () => { useField('name'); }); it('also should call with options', () => { useField({ name: 'name' }); }); it('should raise error when pass object without required prop `name`', () => { // $FlowExpectedError[incompatible-call] useField({ __name: 'name' }); }); it('should return field props', () => { const [props, meta] = useField<number>('name'); (props.value: number); // $FlowExpectedError[incompatible-cast] - check any (props.value: boolean); (meta.touched: boolean); // $FlowExpectedError[incompatible-cast] - check any (meta.touched: number); (meta.error: ?string); // $FlowExpectedError[incompatible-cast] - check any (meta.error: number); }); it('should return FieldHelperProps', () => { const [, , helpers] = useField<string>('name'); helpers.setValue('a name'); helpers.setValue('a name', false); helpers.setTouched(true); helpers.setTouched(true, false); helpers.setError('an error'); }); }); describe('Field and FastField', () => { it('should render Field component', () => { <Field name={'email'} />; <FastField name={'email'} />; }); it('should raise an error when pass incompatible name prop', () => { // $FlowExpectedError[incompatible-type] - `name` must be a string <Field name={111} />; // $FlowExpectedError[prop-missing] - `name` is required prop <Field />; // $FlowExpectedError[prop-missing] - `name` is required prop <FastField />; }); it('should validate value', () => { Field<{ disabled: boolean, ... }, '1' | '2'>({ name: 'count', disabled: true, value: '1', }); Field<{ disabled: boolean, ... }, '1' | '2'>({ name: 'count', // $FlowExpectedError[incompatible-call] - need a boolean disabled: 123, // $FlowExpectedError[incompatible-call] - `12` is missing in enum value: '12', }); }); }); describe('utils', () => { it('should work properly', () => { (isFunction(() => {}): boolean); (isObject({}): boolean); (isInteger(1): boolean); (isString(''): boolean); (isNaN(1 / 0): boolean); (isEmptyChildren([]): boolean); (isPromise(Promise.resolve(1)): boolean); (isInputEvent({}): boolean); (getActiveElement(document): Element | null); getIn({ a: { b: 2 } }, ['a', 'b']); setIn({ a: { b: 2 } }, 'a', 3); setNestedObjectValues({}, 1); }); }); describe('FormikContext', () => { it('should work properly', () => { <FormikConsumer> {value => { (value.validateOnBlur: ?boolean); // $FlowExpectedError[incompatible-cast] - check any (value.validateOnBlur: ?string); (value.submitForm: () => Promise<void>); // $FlowExpectedError[incompatible-cast] - check any (value.submitForm: number); return null; }} </FormikConsumer>; // $FlowExpectedError[incompatible-type] - need valid formik context value <FormikProvider value={123} />; }); it('should return context with passed values', () => { const context = useFormikContext<{ age: number, ... }>(); (context.values.age: number); // $FlowExpectedError[incompatible-cast] - check any (context.values.age: string); }); }); describe('ErrorMessage', () => { it('should work properly', () => { <ErrorMessage name={'password'} />; <ErrorMessage name={'password'} className={undefined} component={undefined} render={undefined} > {undefined} </ErrorMessage>; <ErrorMessage name={'password'} className={'c-error'} component={'div'} render={val => { (val: string); return null; }} > {val => { (val: string); return null; }} </ErrorMessage>; }); it('should raise an error when do not pass required prop `name`', () => { // $FlowExpectedError[prop-missing] <ErrorMessage />; }); }); describe('FieldArray', () => { describe('methods', () => { (move([1], 1, 1): Array<number>); (swap(['str'], 1, 1): Array<string>); (insert([true], 1, false): Array<boolean>); (replace(['1'], 1, '2'): Array<string>); }); describe('Component', () => { it('should render FieldArray component', () => { <FieldArray name={'email'} />; }); it('should raise an error when pass incompatible name prop', () => { // $FlowExpectedError[incompatible-type] - `name` must be a string <FieldArray name={111} />; // $FlowExpectedError[prop-missing] - `name` is required prop <FieldArray />; }); }); }); it('should render Form', () => { <Form />; <Form aria-hidden={'true'} />; // $FlowExpectedError[incompatible-type] - `onSubmit` already provided to `form` yuo can't overwrite it <Form onSubmit={() => {}} />; // $FlowExpectedError[incompatible-type] - `onReset` already provided to `form` yuo can't overwrite it <Form onReset={() => {}} />; }); describe('Formik', () => { describe('Component', () => { it('should work properly', () => { <Formik onSubmit={() => {}} />; }); it('onSumbit can return promise', () => { <Formik onSubmit={() => Promise.resolve(null)} />; }); }); describe('hook', () => { it('should work properly', () => { type Vals = {| name: string, age: number, |}; const formik = useFormik<Vals>({ onSubmit: () => {} }); formik.setFieldValue('name', '1', true); // $FlowExpectedError[prop-missing] - `name` is missing in `Values` formik.setFieldValue('__name', '1'); // $FlowExpectedError[incompatible-call] - `name` expect string value, not `123` formik.setFieldValue('name', 123); (formik.values.name: string); (formik.values.age: number); // $FlowExpectedError[incompatible-cast] - check any (formik.values.name: boolean); // $FlowExpectedError[incompatible-cast] - check any (formik.values.age: boolean); }); }); });
src/js/admin/articles/article-table/article-table-label/article-table-label.js
ucev/blog
import React from 'react' import { connect } from 'react-redux' import TableLabel from '$components/tables/table-label' import { allChecked } from '$actions/articles' class ArticleTableLabel extends React.Component { constructor (props) { super(props) this.handleCheckStateChange = this.handleCheckStateChange.bind(this) } handleCheckStateChange (e) { this.props.checkAll(e.target.checked) e.stopPropagation() } render () { var checked = this.props.allCheckState == true ? 'checked' : '' var labels = [ { name: 'check', val: ( <input type="checkbox" checked={checked} onChange={this.handleCheckStateChange} /> ), }, { name: 'index', val: '序号' }, { name: 'title', val: '标题' }, { name: 'category', val: '类别' }, { name: 'label', val: '标签' }, { name: 'status', val: '状态' }, { name: 'pageview', val: '阅读次数' }, { name: 'operation', val: '操作' }, ] return <TableLabel key={1} type="article" labels={labels} /> } } const mapStateToProps = state => ({ allCheckState: state.articles.every(article => state.checkState[article.id]), }) const mapDispatchToProps = dispatch => ({ checkAll: checked => { dispatch(allChecked(checked)) }, }) const _ArticleTableLabel = connect( mapStateToProps, mapDispatchToProps )(ArticleTableLabel) export default _ArticleTableLabel
fields/types/embedly/EmbedlyField.js
frontyard/keystone
import React from 'react'; import Field from '../Field'; import { FormField, FormInput } from '../../../admin/client/App/elemental'; import ImageThumbnail from '../../components/ImageThumbnail'; import NestedFormField from '../../components/NestedFormField'; module.exports = Field.create({ displayName: 'EmbedlyField', statics: { type: 'Embedly', getDefaultValue: () => ({}), }, // always defers to renderValue; there is no form UI for this field renderField () { return this.renderValue(); }, renderValue (path, label, multiline) { return ( <NestedFormField key={path} label={label}> <FormInput noedit multiline={multiline}>{this.props.value[path]}</FormInput> </NestedFormField> ); }, renderAuthor () { if (!this.props.value.authorName) return; return ( <NestedFormField key="author" label="Author"> <FormInput noedit href={this.props.value.authorUrl && this.props.value.authorUrl} target="_blank">{this.props.value.authorName}</FormInput> </NestedFormField> ); }, renderDimensions () { if (!this.props.value.width || !this.props.value.height) return; return ( <NestedFormField key="dimensions" label="Dimensions"> <FormInput noedit>{this.props.value.width} &times; {this.props.value.height}px</FormInput> </NestedFormField> ); }, renderPreview () { if (!this.props.value.thumbnailUrl) return; var image = <img width={this.props.value.thumbnailWidth} height={this.props.value.thumbnailHeight} src={this.props.value.thumbnailUrl} />; var preview = this.props.value.url ? ( <ImageThumbnail component="a" href={this.props.value.url} target="_blank"> {image} </ImageThumbnail> ) : ( <ImageThumbnail>{image}</ImageThumbnail> ); return ( <NestedFormField label="Preview"> {preview} </NestedFormField> ); }, renderUI () { if (!this.props.value.exists) { return ( <FormField label={this.props.label}> <FormInput noedit>(not set)</FormInput> </FormField> ); } return ( <div> <FormField key="provider" label={this.props.label}> <FormInput noedit>{this.props.value.providerName} {this.props.value.type}</FormInput> </FormField> {this.renderValue('title', 'Title')} {this.renderAuthor()} {this.renderValue('description', 'Description', true)} {this.renderPreview()} {this.renderDimensions()} </div> ); }, });
node_modules/react-icons/go/credit-card.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const GoCreditCard = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m5 27.5h5v-2.5h-5v2.5z m7.5 0h5v-2.5h-5v2.5z m2.5-7.5h-10v2.5h10v-2.5z m-5-2.5h2.5l5-5h-2.5l-5 5z m7.5 5h7.5v-2.5h-7.5v2.5z m20-15h-35s-2.5 1.3-2.5 2.5v20s1.3 2.5 2.5 2.5h35s2.5-1.2 2.5-2.5v-20s-1.2-2.5-2.5-2.5z m0 10v11.3s0 1.2-1.2 1.2h-32.5c-1.3 0-1.3-1.2-1.3-1.2v-11.3h2.5l5-5h-7.5v-1.2s0-1.3 1.3-1.3h32.5c1.2 0 1.2 1.3 1.2 1.3v1.2h-15l-5 5h20z"/></g> </Icon> ) export default GoCreditCard
src/index.js
johannhof/going-declarative
import './styles/style.scss'; import React from 'react'; import Bacon from 'baconjs'; import location from './location'; import colors from './colors'; import Intro from './slides/intro'; import Flow from './slides/flow'; import HowBacon from './slides/how-bacon'; import Start from './slides/start'; import Flux from './slides/what-about-flux'; import AboutBacon from './slides/about-bacon'; import Alternatives from './slides/alternatives'; import TooMuchReact from './slides/too-much-react'; import BaconAndReact from './slides/bacon-and-react'; import FromTheTrenches from './slides/from-the-trenches'; import TheEnd from './slides/the-end'; const container = document.createElement('div'); document.body.appendChild(container); const fa = document.createElement('link'); fa.href = 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css'; fa.rel = 'stylesheet'; document.head.appendChild(fa); Bacon .combineAsArray(colors.startWith({}), location) .onValues(function(_colors, {slide, sub}){ let el; switch(slide){ case 'the-end': el = <TheEnd sub={sub} />; break; case 'alternatives': el = <Alternatives sub={sub} />; break; case 'too-much-react': el = <TooMuchReact sub={sub} />; break; case 'what-about-flux': el = <Flux sub={sub} />; break; case 'from-the-trenches': el = <FromTheTrenches sub={sub} />; break; case 'how-bacon-works': el = <HowBacon colors={_colors} sub={sub} />; break; case 'bacon-and-react': el = <BaconAndReact sub={sub} />; break; case 'about-bacon': el = <AboutBacon sub={sub} />; break; case 'flow': el = <Flow sub={sub} />; break; case 'intro': el = <Intro sub={sub} />; break; default: el = <Start sub={sub} />; } React.render( <div className="container"> <div className="head" style={{top: 10}}>Going Declarative</div> {el} <div className="head" style={{bottom: 10}}>Johann Hofmann 2015</div> </div> , container); });
packages/material-ui-icons/src/WcSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M.01 0h24v24h-24V0z" /><g><path d="M5.5 22v-7.5H4V7h7v7.5H9.5V22h-4zM18 22v-6h3l-3-9h-3l-3 9h3v6h3zM7.5 6c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2zm9 0c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2z" /></g></React.Fragment> , 'WcSharp');
app/components/H2/index.js
koolkt/react-coloc
import React from 'react'; import styles from './styles.css'; function H2(props) { return ( <h2 className={styles.heading2} { ...props } /> ); } export default H2;
pootle/static/js/auth/components/EmailConfirmation.js
JohnnyKing94/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import { PureRenderMixin } from 'react-addons-pure-render-mixin'; import AuthContent from './AuthContent'; const EmailConfirmation = React.createClass({ propTypes: { onClose: React.PropTypes.func.isRequired, }, mixins: [PureRenderMixin], /* Layout */ render() { return ( <AuthContent> <p>{gettext('This email confirmation link expired or is invalid.')}</p> <div className="actions"> <button className="btn btn-primary" onClick={this.props.onClose} > {gettext('Close')} </button> </div> </AuthContent> ); }, }); export default EmailConfirmation;
src/svg-icons/av/library-music.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvLibraryMusic = (props) => ( <SvgIcon {...props}> <path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 5h-3v5.5c0 1.38-1.12 2.5-2.5 2.5S10 13.88 10 12.5s1.12-2.5 2.5-2.5c.57 0 1.08.19 1.5.51V5h4v2zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6z"/> </SvgIcon> ); AvLibraryMusic = pure(AvLibraryMusic); AvLibraryMusic.displayName = 'AvLibraryMusic'; AvLibraryMusic.muiName = 'SvgIcon'; export default AvLibraryMusic;
src/components/google_map.js
MrmRed/test
import React, { Component } from 'react'; class GoogleMap extends Component{ componentDidMount(){ new GoogleMap.maps.Map( this.refs.map, { zoom: 12, center: { lat: this.props.lat, lng: this.props.lng } } ); } render(){ return <div ref="map"/> } } export default GoogleMap;
libs/zeroclipboard/2.1.6/ZeroClipboard.Core.js
tzq668766/static
/*! * ZeroClipboard * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface. * Copyright (c) 2014 Jon Rohan, James M. Greene * Licensed MIT * http://zeroclipboard.org/ * v2.1.6 */ (function(window, undefined) { "use strict"; /** * Store references to critically important global functions that may be * overridden on certain web pages. */ var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _encodeURIComponent = _window.encodeURIComponent, _ActiveXObject = _window.ActiveXObject, _Error = _window.Error, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _round = _window.Math.round, _now = _window.Date.now, _keys = _window.Object.keys, _defineProperty = _window.Object.defineProperty, _hasOwn = _window.Object.prototype.hasOwnProperty, _slice = _window.Array.prototype.slice, _unwrap = function() { var unwrapper = function(el) { return el; }; if (typeof _window.wrap === "function" && typeof _window.unwrap === "function") { try { var div = _document.createElement("div"); var unwrappedDiv = _window.unwrap(div); if (div.nodeType === 1 && unwrappedDiv && unwrappedDiv.nodeType === 1) { unwrapper = _window.unwrap; } } catch (e) {} } return unwrapper; }(); /** * Convert an `arguments` object into an Array. * * @returns The arguments as an Array * @private */ var _args = function(argumentsObj) { return _slice.call(argumentsObj, 0); }; /** * Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`. * * @returns The target object, augmented * @private */ var _extend = function() { var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {}; for (i = 1, len = args.length; i < len; i++) { if ((arg = args[i]) != null) { for (prop in arg) { if (_hasOwn.call(arg, prop)) { src = target[prop]; copy = arg[prop]; if (target !== copy && copy !== undefined) { target[prop] = copy; } } } } } return target; }; /** * Return a deep copy of the source object or array. * * @returns Object or Array * @private */ var _deepCopy = function(source) { var copy, i, len, prop; if (typeof source !== "object" || source == null) { copy = source; } else if (typeof source.length === "number") { copy = []; for (i = 0, len = source.length; i < len; i++) { if (_hasOwn.call(source, i)) { copy[i] = _deepCopy(source[i]); } } } else { copy = {}; for (prop in source) { if (_hasOwn.call(source, prop)) { copy[prop] = _deepCopy(source[prop]); } } } return copy; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep. * The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to * be kept. * * @returns A new filtered object. * @private */ var _pick = function(obj, keys) { var newObj = {}; for (var i = 0, len = keys.length; i < len; i++) { if (keys[i] in obj) { newObj[keys[i]] = obj[keys[i]]; } } return newObj; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit. * The inverse of `_pick`. * * @returns A new filtered object. * @private */ var _omit = function(obj, keys) { var newObj = {}; for (var prop in obj) { if (keys.indexOf(prop) === -1) { newObj[prop] = obj[prop]; } } return newObj; }; /** * Remove all owned, enumerable properties from an object. * * @returns The original object without its owned, enumerable properties. * @private */ var _deleteOwnProperties = function(obj) { if (obj) { for (var prop in obj) { if (_hasOwn.call(obj, prop)) { delete obj[prop]; } } } return obj; }; /** * Determine if an element is contained within another element. * * @returns Boolean * @private */ var _containedBy = function(el, ancestorEl) { if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) { do { if (el === ancestorEl) { return true; } el = el.parentNode; } while (el); } return false; }; /** * Get the URL path's parent directory. * * @returns String or `undefined` * @private */ var _getDirPathOfUrl = function(url) { var dir; if (typeof url === "string" && url) { dir = url.split("#")[0].split("?")[0]; dir = url.slice(0, url.lastIndexOf("/") + 1); } return dir; }; /** * Get the current script's URL by throwing an `Error` and analyzing it. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrlFromErrorStack = function(stack) { var url, matches; if (typeof stack === "string" && stack) { matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); if (matches && matches[1]) { url = matches[1]; } else { matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); if (matches && matches[1]) { url = matches[1]; } } } return url; }; /** * Get the current script's URL by throwing an `Error` and analyzing it. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrlFromError = function() { var url, err; try { throw new _Error(); } catch (e) { err = e; } if (err) { url = err.sourceURL || err.fileName || _getCurrentScriptUrlFromErrorStack(err.stack); } return url; }; /** * Get the current script's URL. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrl = function() { var jsPath, scripts, i; if (_document.currentScript && (jsPath = _document.currentScript.src)) { return jsPath; } scripts = _document.getElementsByTagName("script"); if (scripts.length === 1) { return scripts[0].src || undefined; } if ("readyState" in scripts[0]) { for (i = scripts.length; i--; ) { if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) { return jsPath; } } } if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) { return jsPath; } if (jsPath = _getCurrentScriptUrlFromError()) { return jsPath; } return undefined; }; /** * Get the unanimous parent directory of ALL script tags. * If any script tags are either (a) inline or (b) from differing parent * directories, this method must return `undefined`. * * @returns String or `undefined` * @private */ var _getUnanimousScriptParentDir = function() { var i, jsDir, jsPath, scripts = _document.getElementsByTagName("script"); for (i = scripts.length; i--; ) { if (!(jsPath = scripts[i].src)) { jsDir = null; break; } jsPath = _getDirPathOfUrl(jsPath); if (jsDir == null) { jsDir = jsPath; } else if (jsDir !== jsPath) { jsDir = null; break; } } return jsDir || undefined; }; /** * Get the presumed location of the "ZeroClipboard.swf" file, based on the location * of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.). * * @returns String * @private */ var _getDefaultSwfPath = function() { var jsDir = _getDirPathOfUrl(_getCurrentScriptUrl()) || _getUnanimousScriptParentDir() || ""; return jsDir + "ZeroClipboard.swf"; }; /** * Keep track of the state of the Flash object. * @private */ var _flashState = { bridge: null, version: "0.0.0", pluginType: "unknown", disabled: null, outdated: null, unavailable: null, deactivated: null, overdue: null, ready: null }; /** * The minimum Flash Player version required to use ZeroClipboard completely. * @readonly * @private */ var _minimumFlashVersion = "11.0.0"; /** * Keep track of all event listener registrations. * @private */ var _handlers = {}; /** * Keep track of the currently activated element. * @private */ var _currentElement; /** * Keep track of the element that was activated when a `copy` process started. * @private */ var _copyTarget; /** * Keep track of data for the pending clipboard transaction. * @private */ var _clipData = {}; /** * Keep track of data formats for the pending clipboard transaction. * @private */ var _clipDataFormatMap = null; /** * The `message` store for events * @private */ var _eventMessages = { ready: "Flash communication is established", error: { "flash-disabled": "Flash is disabled or not installed", "flash-outdated": "Flash is too outdated to support ZeroClipboard", "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript", "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate", "flash-overdue": "Flash communication was established but NOT within the acceptable time limit" } }; /** * ZeroClipboard configuration defaults for the Core module. * @private */ var _globalConfig = { swfPath: _getDefaultSwfPath(), trustedDomains: window.location.host ? [ window.location.host ] : [], cacheBust: true, forceEnhancedClipboard: false, flashLoadTimeout: 3e4, autoActivate: true, bubbleEvents: true, containerId: "global-zeroclipboard-html-bridge", containerClass: "global-zeroclipboard-container", swfObjectId: "global-zeroclipboard-flash-bridge", hoverClass: "zeroclipboard-is-hover", activeClass: "zeroclipboard-is-active", forceHandCursor: false, title: null, zIndex: 999999999 }; /** * The underlying implementation of `ZeroClipboard.config`. * @private */ var _config = function(options) { if (typeof options === "object" && options !== null) { for (var prop in options) { if (_hasOwn.call(options, prop)) { if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) { _globalConfig[prop] = options[prop]; } else if (_flashState.bridge == null) { if (prop === "containerId" || prop === "swfObjectId") { if (_isValidHtml4Id(options[prop])) { _globalConfig[prop] = options[prop]; } else { throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID"); } } else { _globalConfig[prop] = options[prop]; } } } } } if (typeof options === "string" && options) { if (_hasOwn.call(_globalConfig, options)) { return _globalConfig[options]; } return; } return _deepCopy(_globalConfig); }; /** * The underlying implementation of `ZeroClipboard.state`. * @private */ var _state = function() { return { browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]), flash: _omit(_flashState, [ "bridge" ]), zeroclipboard: { version: ZeroClipboard.version, config: ZeroClipboard.config() } }; }; /** * The underlying implementation of `ZeroClipboard.isFlashUnusable`. * @private */ var _isFlashUnusable = function() { return !!(_flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated); }; /** * The underlying implementation of `ZeroClipboard.on`. * @private */ var _on = function(eventType, listener) { var i, len, events, added = {}; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!_handlers[eventType]) { _handlers[eventType] = []; } _handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { ZeroClipboard.emit({ type: "ready" }); } if (added.error) { var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ]; for (i = 0, len = errorTypes.length; i < len; i++) { if (_flashState[errorTypes[i]] === true) { ZeroClipboard.emit({ type: "error", name: "flash-" + errorTypes[i] }); break; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.off`. * @private */ var _off = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers; if (arguments.length === 0) { events = _keys(_handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = _handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = perEventHandlers.indexOf(listener); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = perEventHandlers.indexOf(listener, foundIndex); } } else { perEventHandlers.length = 0; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.handlers`. * @private */ var _listeners = function(eventType) { var copy; if (typeof eventType === "string" && eventType) { copy = _deepCopy(_handlers[eventType]) || null; } else { copy = _deepCopy(_handlers); } return copy; }; /** * The underlying implementation of `ZeroClipboard.emit`. * @private */ var _emit = function(event) { var eventCopy, returnVal, tmp; event = _createEvent(event); if (!event) { return; } if (_preprocessEvent(event)) { return; } if (event.type === "ready" && _flashState.overdue === true) { return ZeroClipboard.emit({ type: "error", name: "flash-overdue" }); } eventCopy = _extend({}, event); _dispatchCallbacks.call(this, eventCopy); if (event.type === "copy") { tmp = _mapClipDataToFlash(_clipData); returnVal = tmp.data; _clipDataFormatMap = tmp.formatMap; } return returnVal; }; /** * The underlying implementation of `ZeroClipboard.create`. * @private */ var _create = function() { if (typeof _flashState.ready !== "boolean") { _flashState.ready = false; } if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) { var maxWait = _globalConfig.flashLoadTimeout; if (typeof maxWait === "number" && maxWait >= 0) { _setTimeout(function() { if (typeof _flashState.deactivated !== "boolean") { _flashState.deactivated = true; } if (_flashState.deactivated === true) { ZeroClipboard.emit({ type: "error", name: "flash-deactivated" }); } }, maxWait); } _flashState.overdue = false; _embedSwf(); } }; /** * The underlying implementation of `ZeroClipboard.destroy`. * @private */ var _destroy = function() { ZeroClipboard.clearData(); ZeroClipboard.blur(); ZeroClipboard.emit("destroy"); _unembedSwf(); ZeroClipboard.off(); }; /** * The underlying implementation of `ZeroClipboard.setData`. * @private */ var _setData = function(format, data) { var dataObj; if (typeof format === "object" && format && typeof data === "undefined") { dataObj = format; ZeroClipboard.clearData(); } else if (typeof format === "string" && format) { dataObj = {}; dataObj[format] = data; } else { return; } for (var dataFormat in dataObj) { if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) { _clipData[dataFormat] = dataObj[dataFormat]; } } }; /** * The underlying implementation of `ZeroClipboard.clearData`. * @private */ var _clearData = function(format) { if (typeof format === "undefined") { _deleteOwnProperties(_clipData); _clipDataFormatMap = null; } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { delete _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.getData`. * @private */ var _getData = function(format) { if (typeof format === "undefined") { return _deepCopy(_clipData); } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { return _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`. * @private */ var _focus = function(element) { if (!(element && element.nodeType === 1)) { return; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.activeClass); if (_currentElement !== element) { _removeClass(_currentElement, _globalConfig.hoverClass); } } _currentElement = element; _addClass(element, _globalConfig.hoverClass); var newTitle = element.getAttribute("title") || _globalConfig.title; if (typeof newTitle === "string" && newTitle) { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.setAttribute("title", newTitle); } } var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer"; _setHandCursor(useHandCursor); _reposition(); }; /** * The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`. * @private */ var _blur = function() { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.removeAttribute("title"); htmlBridge.style.left = "0px"; htmlBridge.style.top = "-9999px"; htmlBridge.style.width = "1px"; htmlBridge.style.top = "1px"; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); _currentElement = null; } }; /** * The underlying implementation of `ZeroClipboard.activeElement`. * @private */ var _activeElement = function() { return _currentElement || null; }; /** * Check if a value is a valid HTML4 `ID` or `Name` token. * @private */ var _isValidHtml4Id = function(id) { return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id); }; /** * Create or update an `event` object, based on the `eventType`. * @private */ var _createEvent = function(event) { var eventType; if (typeof event === "string" && event) { eventType = event; event = {}; } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) { eventType = event.type; } if (!eventType) { return; } if (!event.target && /^(copy|aftercopy|_click)$/.test(eventType.toLowerCase())) { event.target = _copyTarget; } _extend(event, { type: eventType.toLowerCase(), target: event.target || _currentElement || null, relatedTarget: event.relatedTarget || null, currentTarget: _flashState && _flashState.bridge || null, timeStamp: event.timeStamp || _now() || null }); var msg = _eventMessages[event.type]; if (event.type === "error" && event.name && msg) { msg = msg[event.name]; } if (msg) { event.message = msg; } if (event.type === "ready") { _extend(event, { target: null, version: _flashState.version }); } if (event.type === "error") { if (/^flash-(disabled|outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { target: null, minimumVersion: _minimumFlashVersion }); } if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { version: _flashState.version }); } } if (event.type === "copy") { event.clipboardData = { setData: ZeroClipboard.setData, clearData: ZeroClipboard.clearData }; } if (event.type === "aftercopy") { event = _mapClipResultsFromFlash(event, _clipDataFormatMap); } if (event.target && !event.relatedTarget) { event.relatedTarget = _getRelatedTarget(event.target); } event = _addMouseData(event); return event; }; /** * Get a relatedTarget from the target's `data-clipboard-target` attribute * @private */ var _getRelatedTarget = function(targetEl) { var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target"); return relatedTargetId ? _document.getElementById(relatedTargetId) : null; }; /** * Add element and position data to `MouseEvent` instances * @private */ var _addMouseData = function(event) { if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { var srcElement = event.target; var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined; var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined; var pos = _getDOMObjectPosition(srcElement); var screenLeft = _window.screenLeft || _window.screenX || 0; var screenTop = _window.screenTop || _window.screenY || 0; var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft; var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop; var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0); var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0); var clientX = pageX - scrollLeft; var clientY = pageY - scrollTop; var screenX = screenLeft + clientX; var screenY = screenTop + clientY; var moveX = typeof event.movementX === "number" ? event.movementX : 0; var moveY = typeof event.movementY === "number" ? event.movementY : 0; delete event._stageX; delete event._stageY; _extend(event, { srcElement: srcElement, fromElement: fromElement, toElement: toElement, screenX: screenX, screenY: screenY, pageX: pageX, pageY: pageY, clientX: clientX, clientY: clientY, x: clientX, y: clientY, movementX: moveX, movementY: moveY, offsetX: 0, offsetY: 0, layerX: 0, layerY: 0 }); } return event; }; /** * Determine if an event's registered handlers should be execute synchronously or asynchronously. * * @returns {boolean} * @private */ var _shouldPerformAsync = function(event) { var eventType = event && typeof event.type === "string" && event.type || ""; return !/^(?:(?:before)?copy|destroy)$/.test(eventType); }; /** * Control if a callback should be executed asynchronously or not. * * @returns `undefined` * @private */ var _dispatchCallback = function(func, context, args, async) { if (async) { _setTimeout(function() { func.apply(context, args); }, 0); } else { func.apply(context, args); } }; /** * Handle the actual dispatching of events to client instances. * * @returns `undefined` * @private */ var _dispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = _handlers["*"] || []; var specificTypeHandlers = _handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } return this; }; /** * Preprocess any special behaviors, reactions, or state changes after receiving this event. * Executes only once per event emitted, NOT once per client. * @private */ var _preprocessEvent = function(event) { var element = event.target || _currentElement || null; var sourceIsSwf = event._source === "swf"; delete event._source; var flashErrorNames = [ "flash-disabled", "flash-outdated", "flash-unavailable", "flash-deactivated", "flash-overdue" ]; switch (event.type) { case "error": if (flashErrorNames.indexOf(event.name) !== -1) { _extend(_flashState, { disabled: event.name === "flash-disabled", outdated: event.name === "flash-outdated", unavailable: event.name === "flash-unavailable", deactivated: event.name === "flash-deactivated", overdue: event.name === "flash-overdue", ready: false }); } break; case "ready": var wasDeactivated = _flashState.deactivated === true; _extend(_flashState, { disabled: false, outdated: false, unavailable: false, deactivated: false, overdue: wasDeactivated, ready: !wasDeactivated }); break; case "beforecopy": _copyTarget = element; break; case "copy": var textContent, htmlContent, targetEl = event.relatedTarget; if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); if (htmlContent !== textContent) { event.clipboardData.setData("text/html", htmlContent); } } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); } break; case "aftercopy": ZeroClipboard.clearData(); if (element && element !== _safeActiveElement() && element.focus) { element.focus(); } break; case "_mouseover": ZeroClipboard.focus(element); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) { _fireMouseEvent(_extend({}, event, { type: "mouseenter", bubbles: false, cancelable: false })); } _fireMouseEvent(_extend({}, event, { type: "mouseover" })); } break; case "_mouseout": ZeroClipboard.blur(); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) { _fireMouseEvent(_extend({}, event, { type: "mouseleave", bubbles: false, cancelable: false })); } _fireMouseEvent(_extend({}, event, { type: "mouseout" })); } break; case "_mousedown": _addClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mouseup": _removeClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_click": _copyTarget = null; if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mousemove": if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; } if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { return true; } }; /** * Dispatch a synthetic MouseEvent. * * @returns `undefined` * @private */ var _fireMouseEvent = function(event) { if (!(event && typeof event.type === "string" && event)) { return; } var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = { view: doc.defaultView || _window, canBubble: true, cancelable: true, detail: event.type === "click" ? 1 : 0, button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1 }, args = _extend(defaults, event); if (!target) { return; } if (doc.createEvent && target.dispatchEvent) { args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ]; e = doc.createEvent("MouseEvents"); if (e.initMouseEvent) { e.initMouseEvent.apply(e, args); e._source = "js"; target.dispatchEvent(e); } } }; /** * Create the HTML bridge element to embed the Flash object into. * @private */ var _createHtmlBridge = function() { var container = _document.createElement("div"); container.id = _globalConfig.containerId; container.className = _globalConfig.containerClass; container.style.position = "absolute"; container.style.left = "0px"; container.style.top = "-9999px"; container.style.width = "1px"; container.style.height = "1px"; container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); return container; }; /** * Get the HTML element container that wraps the Flash bridge object/element. * @private */ var _getHtmlBridge = function(flashBridge) { var htmlBridge = flashBridge && flashBridge.parentNode; while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) { htmlBridge = htmlBridge.parentNode; } return htmlBridge || null; }; /** * Create the SWF object. * * @returns The SWF object reference. * @private */ var _embedSwf = function() { var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge); if (!flashBridge) { var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig); var allowNetworking = allowScriptAccess === "never" ? "none" : "all"; var flashvars = _vars(_globalConfig); var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig); container = _createHtmlBridge(); var divToBeReplaced = _document.createElement("div"); container.appendChild(divToBeReplaced); _document.body.appendChild(container); var tmpDiv = _document.createElement("div"); var oldIE = _flashState.pluginType === "activex"; tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + "</object>"; flashBridge = tmpDiv.firstChild; tmpDiv = null; _unwrap(flashBridge).ZeroClipboard = ZeroClipboard; container.replaceChild(flashBridge, divToBeReplaced); } if (!flashBridge) { flashBridge = _document[_globalConfig.swfObjectId]; if (flashBridge && (len = flashBridge.length)) { flashBridge = flashBridge[len - 1]; } if (!flashBridge && container) { flashBridge = container.firstChild; } } _flashState.bridge = flashBridge || null; return flashBridge; }; /** * Destroy the SWF object. * @private */ var _unembedSwf = function() { var flashBridge = _flashState.bridge; if (flashBridge) { var htmlBridge = _getHtmlBridge(flashBridge); if (htmlBridge) { if (_flashState.pluginType === "activex" && "readyState" in flashBridge) { flashBridge.style.display = "none"; (function removeSwfFromIE() { if (flashBridge.readyState === 4) { for (var prop in flashBridge) { if (typeof flashBridge[prop] === "function") { flashBridge[prop] = null; } } if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } else { _setTimeout(removeSwfFromIE, 10); } })(); } else { if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } } _flashState.ready = null; _flashState.bridge = null; _flashState.deactivated = null; } }; /** * Map the data format names of the "clipData" to Flash-friendly names. * * @returns A new transformed object. * @private */ var _mapClipDataToFlash = function(clipData) { var newClipData = {}, formatMap = {}; if (!(typeof clipData === "object" && clipData)) { return; } for (var dataFormat in clipData) { if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) { switch (dataFormat.toLowerCase()) { case "text/plain": case "text": case "air:text": case "flash:text": newClipData.text = clipData[dataFormat]; formatMap.text = dataFormat; break; case "text/html": case "html": case "air:html": case "flash:html": newClipData.html = clipData[dataFormat]; formatMap.html = dataFormat; break; case "application/rtf": case "text/rtf": case "rtf": case "richtext": case "air:rtf": case "flash:rtf": newClipData.rtf = clipData[dataFormat]; formatMap.rtf = dataFormat; break; default: break; } } } return { data: newClipData, formatMap: formatMap }; }; /** * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping). * * @returns A new transformed object. * @private */ var _mapClipResultsFromFlash = function(clipResults, formatMap) { if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) { return clipResults; } var newResults = {}; for (var prop in clipResults) { if (_hasOwn.call(clipResults, prop)) { if (prop !== "success" && prop !== "data") { newResults[prop] = clipResults[prop]; continue; } newResults[prop] = {}; var tmpHash = clipResults[prop]; for (var dataFormat in tmpHash) { if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) { newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat]; } } } } return newResults; }; /** * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}" * query param string to return. Does NOT append that string to the original path. * This is useful because ExternalInterface often breaks when a Flash SWF is cached. * * @returns The `noCache` query param with necessary "?"/"&" prefix. * @private */ var _cacheBust = function(path, options) { var cacheBust = options == null || options && options.cacheBust === true; if (cacheBust) { return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now(); } else { return ""; } }; /** * Creates a query string for the FlashVars param. * Does NOT include the cache-busting query param. * * @returns FlashVars query string * @private */ var _vars = function(options) { var i, len, domain, domains, str = "", trustedOriginsExpanded = []; if (options.trustedDomains) { if (typeof options.trustedDomains === "string") { domains = [ options.trustedDomains ]; } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) { domains = options.trustedDomains; } } if (domains && domains.length) { for (i = 0, len = domains.length; i < len; i++) { if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") { domain = _extractDomain(domains[i]); if (!domain) { continue; } if (domain === "*") { trustedOriginsExpanded.length = 0; trustedOriginsExpanded.push(domain); break; } trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]); } } } if (trustedOriginsExpanded.length) { str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(",")); } if (options.forceEnhancedClipboard === true) { str += (str ? "&" : "") + "forceEnhancedClipboard=true"; } if (typeof options.swfObjectId === "string" && options.swfObjectId) { str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId); } return str; }; /** * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/"). * * @returns the domain * @private */ var _extractDomain = function(originOrUrl) { if (originOrUrl == null || originOrUrl === "") { return null; } originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, ""); if (originOrUrl === "") { return null; } var protocolIndex = originOrUrl.indexOf("//"); originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2); var pathIndex = originOrUrl.indexOf("/"); originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex); if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") { return null; } return originOrUrl || null; }; /** * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`. * * @returns The appropriate script access level. * @private */ var _determineScriptAccess = function() { var _extractAllDomains = function(origins) { var i, len, tmp, resultsArray = []; if (typeof origins === "string") { origins = [ origins ]; } if (!(typeof origins === "object" && origins && typeof origins.length === "number")) { return resultsArray; } for (i = 0, len = origins.length; i < len; i++) { if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) { if (tmp === "*") { resultsArray.length = 0; resultsArray.push("*"); break; } if (resultsArray.indexOf(tmp) === -1) { resultsArray.push(tmp); } } } return resultsArray; }; return function(currentDomain, configOptions) { var swfDomain = _extractDomain(configOptions.swfPath); if (swfDomain === null) { swfDomain = currentDomain; } var trustedDomains = _extractAllDomains(configOptions.trustedDomains); var len = trustedDomains.length; if (len > 0) { if (len === 1 && trustedDomains[0] === "*") { return "always"; } if (trustedDomains.indexOf(currentDomain) !== -1) { if (len === 1 && currentDomain === swfDomain) { return "sameDomain"; } return "always"; } } return "never"; }; }(); /** * Get the currently active/focused DOM element. * * @returns the currently active/focused element, or `null` * @private */ var _safeActiveElement = function() { try { return _document.activeElement; } catch (err) { return null; } }; /** * Add a class to an element, if it doesn't already have it. * * @returns The element, with its new class added. * @private */ var _addClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (!element.classList.contains(value)) { element.classList.add(value); } return element; } if (value && typeof value === "string") { var classNames = (value || "").split(/\s+/); if (element.nodeType === 1) { if (!element.className) { element.className = value; } else { var className = " " + element.className + " ", setClass = element.className; for (var c = 0, cl = classNames.length; c < cl; c++) { if (className.indexOf(" " + classNames[c] + " ") < 0) { setClass += " " + classNames[c]; } } element.className = setClass.replace(/^\s+|\s+$/g, ""); } } } return element; }; /** * Remove a class from an element, if it has it. * * @returns The element, with its class removed. * @private */ var _removeClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (element.classList.contains(value)) { element.classList.remove(value); } return element; } if (typeof value === "string" && value) { var classNames = value.split(/\s+/); if (element.nodeType === 1 && element.className) { var className = (" " + element.className + " ").replace(/[\n\t]/g, " "); for (var c = 0, cl = classNames.length; c < cl; c++) { className = className.replace(" " + classNames[c] + " ", " "); } element.className = className.replace(/^\s+|\s+$/g, ""); } } return element; }; /** * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`, * then we assume that it should be a hand ("pointer") cursor if the element * is an anchor element ("a" tag). * * @returns The computed style property. * @private */ var _getStyle = function(el, prop) { var value = _window.getComputedStyle(el, null).getPropertyValue(prop); if (prop === "cursor") { if (!value || value === "auto") { if (el.nodeName === "A") { return "pointer"; } } } return value; }; /** * Get the zoom factor of the browser. Always returns `1.0`, except at * non-default zoom levels in IE<8 and some older versions of WebKit. * * @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`). * @private */ var _getZoomFactor = function() { var rect, physicalWidth, logicalWidth, zoomFactor = 1; if (typeof _document.body.getBoundingClientRect === "function") { rect = _document.body.getBoundingClientRect(); physicalWidth = rect.right - rect.left; logicalWidth = _document.body.offsetWidth; zoomFactor = _round(physicalWidth / logicalWidth * 100) / 100; } return zoomFactor; }; /** * Get the DOM positioning info of an element. * * @returns Object containing the element's position, width, and height. * @private */ var _getDOMObjectPosition = function(obj) { var info = { left: 0, top: 0, width: 0, height: 0 }; if (obj.getBoundingClientRect) { var rect = obj.getBoundingClientRect(); var pageXOffset, pageYOffset, zoomFactor; if ("pageXOffset" in _window && "pageYOffset" in _window) { pageXOffset = _window.pageXOffset; pageYOffset = _window.pageYOffset; } else { zoomFactor = _getZoomFactor(); pageXOffset = _round(_document.documentElement.scrollLeft / zoomFactor); pageYOffset = _round(_document.documentElement.scrollTop / zoomFactor); } var leftBorderWidth = _document.documentElement.clientLeft || 0; var topBorderWidth = _document.documentElement.clientTop || 0; info.left = rect.left + pageXOffset - leftBorderWidth; info.top = rect.top + pageYOffset - topBorderWidth; info.width = "width" in rect ? rect.width : rect.right - rect.left; info.height = "height" in rect ? rect.height : rect.bottom - rect.top; } return info; }; /** * Reposition the Flash object to cover the currently activated element. * * @returns `undefined` * @private */ var _reposition = function() { var htmlBridge; if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) { var pos = _getDOMObjectPosition(_currentElement); _extend(htmlBridge.style, { width: pos.width + "px", height: pos.height + "px", top: pos.top + "px", left: pos.left + "px", zIndex: "" + _getSafeZIndex(_globalConfig.zIndex) }); } }; /** * Sends a signal to the Flash object to display the hand cursor if `true`. * * @returns `undefined` * @private */ var _setHandCursor = function(enabled) { if (_flashState.ready === true) { if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") { _flashState.bridge.setHandCursor(enabled); } else { _flashState.ready = false; } } }; /** * Get a safe value for `zIndex` * * @returns an integer, or "auto" * @private */ var _getSafeZIndex = function(val) { if (/^(?:auto|inherit)$/.test(val)) { return val; } var zIndex; if (typeof val === "number" && !_isNaN(val)) { zIndex = val; } else if (typeof val === "string") { zIndex = _getSafeZIndex(_parseInt(val, 10)); } return typeof zIndex === "number" ? zIndex : "auto"; }; /** * Detect the Flash Player status, version, and plugin type. * * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code} * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript} * * @returns `undefined` * @private */ var _detectFlashSupport = function(ActiveXObject) { var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = ""; /** * Derived from Apple's suggested sniffer. * @param {String} desc e.g. "Shockwave Flash 7.0 r61" * @returns {String} "7.0.61" * @private */ function parseFlashVersion(desc) { var matches = desc.match(/[\d]+/g); matches.length = 3; return matches.join("."); } function isPepperFlash(flashPlayerFileName) { return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin"); } function inspectPlugin(plugin) { if (plugin) { hasFlash = true; if (plugin.version) { flashVersion = parseFlashVersion(plugin.version); } if (!flashVersion && plugin.description) { flashVersion = parseFlashVersion(plugin.description); } if (plugin.filename) { isPPAPI = isPepperFlash(plugin.filename); } } } if (_navigator.plugins && _navigator.plugins.length) { plugin = _navigator.plugins["Shockwave Flash"]; inspectPlugin(plugin); if (_navigator.plugins["Shockwave Flash 2.0"]) { hasFlash = true; flashVersion = "2.0.0.11"; } } else if (_navigator.mimeTypes && _navigator.mimeTypes.length) { mimeType = _navigator.mimeTypes["application/x-shockwave-flash"]; plugin = mimeType && mimeType.enabledPlugin; inspectPlugin(plugin); } else if (typeof ActiveXObject !== "undefined") { isActiveX = true; try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e1) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); hasFlash = true; flashVersion = "6.0.21"; } catch (e2) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e3) { isActiveX = false; } } } } _flashState.disabled = hasFlash !== true; _flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion); _flashState.version = flashVersion || "0.0.0"; _flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown"; }; /** * Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later. */ _detectFlashSupport(_ActiveXObject); /** * A shell constructor for `ZeroClipboard` client instances. * * @constructor */ var ZeroClipboard = function() { if (!(this instanceof ZeroClipboard)) { return new ZeroClipboard(); } if (typeof ZeroClipboard._createClient === "function") { ZeroClipboard._createClient.apply(this, _args(arguments)); } }; /** * The ZeroClipboard library's version number. * * @static * @readonly * @property {string} */ _defineProperty(ZeroClipboard, "version", { value: "2.1.6", writable: false, configurable: true, enumerable: true }); /** * Update or get a copy of the ZeroClipboard global configuration. * Returns a copy of the current/updated configuration. * * @returns Object * @static */ ZeroClipboard.config = function() { return _config.apply(this, _args(arguments)); }; /** * Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard. * * @returns Object * @static */ ZeroClipboard.state = function() { return _state.apply(this, _args(arguments)); }; /** * Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc. * * @returns Boolean * @static */ ZeroClipboard.isFlashUnusable = function() { return _isFlashUnusable.apply(this, _args(arguments)); }; /** * Register an event listener. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.on = function() { return _on.apply(this, _args(arguments)); }; /** * Unregister an event listener. * If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`. * If no `eventType` is provided, it will unregister all listeners for every event type. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.off = function() { return _off.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType`. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.handlers = function() { return _listeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. * @static */ ZeroClipboard.emit = function() { return _emit.apply(this, _args(arguments)); }; /** * Create and embed the Flash object. * * @returns The Flash object * @static */ ZeroClipboard.create = function() { return _create.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything, including the embedded Flash object. * * @returns `undefined` * @static */ ZeroClipboard.destroy = function() { return _destroy.apply(this, _args(arguments)); }; /** * Set the pending data for clipboard injection. * * @returns `undefined` * @static */ ZeroClipboard.setData = function() { return _setData.apply(this, _args(arguments)); }; /** * Clear the pending data for clipboard injection. * If no `format` is provided, all pending data formats will be cleared. * * @returns `undefined` * @static */ ZeroClipboard.clearData = function() { return _clearData.apply(this, _args(arguments)); }; /** * Get a copy of the pending data for clipboard injection. * If no `format` is provided, a copy of ALL pending data formats will be returned. * * @returns `String` or `Object` * @static */ ZeroClipboard.getData = function() { return _getData.apply(this, _args(arguments)); }; /** * Sets the current HTML object that the Flash object should overlay. This will put the global * Flash object on top of the current element; depending on the setup, this may also set the * pending clipboard text data as well as the Flash object's wrapping element's title attribute * based on the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.focus = ZeroClipboard.activate = function() { return _focus.apply(this, _args(arguments)); }; /** * Un-overlays the Flash object. This will put the global Flash object off-screen; depending on * the setup, this may also unset the Flash object's wrapping element's title attribute based on * the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.blur = ZeroClipboard.deactivate = function() { return _blur.apply(this, _args(arguments)); }; /** * Returns the currently focused/"activated" HTML element that the Flash object is wrapping. * * @returns `HTMLElement` or `null` * @static */ ZeroClipboard.activeElement = function() { return _activeElement.apply(this, _args(arguments)); }; if (typeof define === "function" && define.amd) { define(function() { return ZeroClipboard; }); } else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) { module.exports = ZeroClipboard; } else { window.ZeroClipboard = ZeroClipboard; } })(function() { return this || window; }());
docs/src/app/components/pages/components/List/ExampleContacts.js
hai-cea/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import Divider from 'material-ui/Divider'; import Avatar from 'material-ui/Avatar'; import {pinkA200, transparent} from 'material-ui/styles/colors'; const ListExampleContacts = () => ( <MobileTearSheet> <List> <ListItem primaryText="Chelsea Otakan" leftIcon={<ActionGrade color={pinkA200} />} rightAvatar={<Avatar src="images/chexee-128.jpg" />} /> <ListItem primaryText="Eric Hoffman" insetChildren={true} rightAvatar={<Avatar src="images/kolage-128.jpg" />} /> <ListItem primaryText="James Anderson" insetChildren={true} rightAvatar={<Avatar src="images/jsa-128.jpg" />} /> <ListItem primaryText="Kerem Suer" insetChildren={true} rightAvatar={<Avatar src="images/kerem-128.jpg" />} /> </List> <Divider inset={true} /> <List> <ListItem primaryText="Adelle Charles" leftAvatar={ <Avatar color={pinkA200} backgroundColor={transparent} style={{left: 8}} > A </Avatar> } rightAvatar={<Avatar src="images/adellecharles-128.jpg" />} /> <ListItem primaryText="Adham Dannaway" insetChildren={true} rightAvatar={<Avatar src="images/adhamdannaway-128.jpg" />} /> <ListItem primaryText="Allison Grayce" insetChildren={true} rightAvatar={<Avatar src="images/allisongrayce-128.jpg" />} /> <ListItem primaryText="Angel Ceballos" insetChildren={true} rightAvatar={<Avatar src="images/angelceballos-128.jpg" />} /> </List> </MobileTearSheet> ); export default ListExampleContacts;
blog/src/index.js
murielg/react-redux
import _ from 'lodash'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import promise from 'redux-promise'; import reducers from './reducers'; import PostsIndex from './components/posts_index'; import PostsNew from './components/posts_new'; import PostsShow from './components/posts_show'; import './scss/style.scss'; const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path="/posts/new" component={PostsNew} /> <Route path="/posts/:id" component={PostsShow} /> <Route path="/" component={PostsIndex} /> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));